Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running background tasks in node-webkit (nw)

Tags:

node-webkit

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?

like image 245
Anthony O. Avatar asked Sep 06 '15 17:09

Anthony O.


1 Answers

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>
like image 175
Anthony O. Avatar answered Jan 03 '23 13:01

Anthony O.