5

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?

Anthony O.
  • 22,041
  • 18
  • 107
  • 163
  • Out of curiosity, do you have any reasons to use nw.js over electron? i'm using nw.js at the moment, but wanting to give a shot to electron. – kroe Oct 02 '15 at 06:33
  • Yes completly: I couldn't find a good way to debug en electron app... see my other question here: http://stackoverflow.com/questions/32348540/how-to-debug-electron-applications-with-intellij-or-webstorm – Anthony O. Oct 02 '15 at 07:28

1 Answers1

9

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>
Anthony O.
  • 22,041
  • 18
  • 107
  • 163
  • which nw.js version are you using? i'm using 0.8 ( due to having some sqlite already compiled to win / mac, will try to upload soon ) and all i get is "Cannot extract package" when trying to use the fork method on my node-main file. – kroe Oct 02 '15 at 07:21
  • 1
    I'm using the very last one: 0.12.3 – Anthony O. Oct 02 '15 at 07:32
  • i'll try this now and hope sqlite3 can work on osx and windows targetting that version. ( thanks for your fast replies ). – kroe Oct 02 '15 at 07:35
  • Just saw that sqlite3 won't build for nw.js 0.12.3 so i'm locked into 0.8.6 ( and perhaps 0.10 ), i'll have to try this out again soon, need other parts of the app to go ahead at the moment. – kroe Oct 02 '15 at 08:26
  • Yes, you just have to use [`nw-gyp`](https://github.com/nwjs/nw-gyp) in order to get it working – Anthony O. Oct 02 '15 at 15:44