在node-webkit(nw)中运行后台任务

Ant*_* O. 5 node-webkit

我正在尝试使用NW.js运行后台任务(文件系统扫描程序).

电子,这是可以做到用,并呼吁和主脚本,并在孩子的脚本.child_process.fork(__dirname + '/path_to_js_file')child.on('message', function(param) { ... })child.send(...)process.on('message', function(param) { ... })process.send(...)

在NW.js中,我尝试使用Web Workers但没有任何反应(我的webworker脚本从未执行过).

我还看到有一种解决方法,child_process.fork("path_to_js_file.js", {silent: true, execPath:'/path/to/node'})但这意味着将Node.js捆绑到我未来的应用程序中...

另一个想法?

Ant*_* O. 9

这是我最终做的.

package.json声明这样的node-main属性:

{
  "main": "index.html",
  "node-main": "main.js"
}
Run Code Online (Sandbox Code Playgroud)

然后在你的main.js使用中require('child_process').fork:

'use strict';

var fork = require('child_process').fork,
    childProcess = fork('childProcess.js');

exports.childProcess = childProcess;
Run Code Online (Sandbox Code Playgroud)

childProcess.js使用process.on('message', ...)和沟通process.send(...):

process.on('message', function (param) {
    childProcessing(param, function (err, result) {
        if (err) {
            console.error(err.stack);
        } else {
            process.send(result);
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

最后index.html,使用child_process.on('message', ...)child_process.send(...):

    <script>
        var childProcess = process.mainModule.exports.childProcess;
        childProcess.on('message', function (result) {
            console.log(result);
        });
        childProcess.send('my child param');
    </script>
Run Code Online (Sandbox Code Playgroud)