I tried to implement the w3schools demo of web worker on nodejs, but it doesn't work. The OS is Windows 10 (v10.0.18363.1256), Chrome (v88.0.4324.104) is set on developer mode and nodejs (x64-v14.15.4). No errors appear both on the browser and command prompt, which tells me that it's all ok (Server running at http://127.0.0.1:80/). The web page appears, but the buttons don't work. You can read the code below. The file myapp.js to start the node is in my own user folder, whereas demo_worker.js and index.html are in the folder c:\nodejsworker. Thank you in advance for your help.
// demo_workers.js
var i = 0;
function timedCount() {
i = i + 1;
postMessage(i);
setTimeout("timedCount()", 500);
}
timedCount();
//myapp.js
const http = require('http');
var fs = require('fs');
const hostname = '127.0.0.1';
const port = 80;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
// res.end('Hello World');
var myReadStream = fs.createReadStream('C:/nodejsworker/index.html', 'utf8');
myReadStream.pipe(res);
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
<!DOCTYPE html>
<html>
<body>
<p>Count numbers: <output id="result"></output></p>
<button onclick="startWorker()">Start Worker</button>
<button onclick="stopWorker()">Stop Worker</button>
<script>
var w;
function startWorker() {
if (typeof(Worker) !== "undefined") {
if (typeof(w) == "undefined") {
w = new Worker("./demo_workers.js");
}
w.onmessage = function(event) {
document.getElementById("result").innerHTML = event.data;
};
} else {
document.getElementById("result").innerHTML = "Sorry! No Web Worker support.";
}
}
function stopWorker() {
w.terminate();
w = undefined;
}
</script>
</body>
</html>
Aucun commentaire:
Enregistrer un commentaire