I'm trying to run background tasks (file system scanner) using NW.js.
In Electron, it can be done using child_process.fork
(__dirname + '/path_to_js_file')
and calling child.on('message', function(param) { ... })
and child.send(...)
in the main script and process.on('message', function(param) { ... })
and process.send(...)
in the child script.
In NW.js, I tried to use Web Workers but nothing happens (my webworker script is never executed).
I also saw there is a workaround using child_process.fork("path_to_js_file.js", {silent: true, execPath:'/path/to/node'})
but that implies bundling Node.js into my future app...
Another idea?
Here is what I finally did.
In package.json
declare a node-main
property like that:
{
"main": "index.html",
"node-main": "main.js"
}
Then in your main.js
use require('child_process').fork
:
'use strict';
var fork = require('child_process').fork,
childProcess = fork('childProcess.js');
exports.childProcess = childProcess;
In childProcess.js
communicate using process.on('message', ...)
and process.send(...)
:
process.on('message', function (param) {
childProcessing(param, function (err, result) {
if (err) {
console.error(err.stack);
} else {
process.send(result);
}
});
});
And finaly in index.html
, use child_process.on('message', ...)
and child_process.send(...)
:
<script>
var childProcess = process.mainModule.exports.childProcess;
childProcess.on('message', function (result) {
console.log(result);
});
childProcess.send('my child param');
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With