运行 node-webkit 中的后台任务(nw)
Running background tasks in node-webkit (nw)
我正在尝试 运行 使用 NW.js 的后台任务(文件系统扫描器)。
在主脚本中的 Electron, it can be done using child_process.fork
(__dirname + '/path_to_js_file')
and calling child.on('message', function(param) { ... })
and 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 捆绑到我未来的应用程序中...
另一个想法?
这是我最后做的。
在 package.json
中声明一个 node-main
属性 像这样:
{
"main": "index.html",
"node-main": "main.js"
}
然后在你的 main.js
中使用 require('child_process').fork
:
'use strict';
var fork = require('child_process').fork,
childProcess = fork('childProcess.js');
exports.childProcess = childProcess;
在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);
}
});
});
最后在 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>
我正在尝试 运行 使用 NW.js 的后台任务(文件系统扫描器)。
在主脚本中的 Electron, it can be done using child_process.fork
(__dirname + '/path_to_js_file')
and calling child.on('message', function(param) { ... })
and 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 捆绑到我未来的应用程序中...
另一个想法?
这是我最后做的。
在 package.json
中声明一个 node-main
属性 像这样:
{
"main": "index.html",
"node-main": "main.js"
}
然后在你的 main.js
中使用 require('child_process').fork
:
'use strict';
var fork = require('child_process').fork,
childProcess = fork('childProcess.js');
exports.childProcess = childProcess;
在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);
}
});
});
最后在 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>