【问题标题】:Running background tasks in node-webkit (nw)在 node-webkit (nw) 中运行后台任务
【发布时间】:2015-12-02 06:34:29
【问题描述】:

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

Electron 中,可以使用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 捆绑到我未来的应用程序中......

另一个想法?

【问题讨论】:

  • 出于好奇,你有什么理由使用 nw.js 而不是 electron?我目前正在使用 nw.js,但想尝试一下 electron。
  • 完全是的:我找不到调试电子应用程序的好方法...在这里查看我的另一个问题:stackoverflow.com/questions/32348540/…

标签: node-webkit


【解决方案1】:

这就是我最终所做的。

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 版本?我正在使用 0.8 (由于一些 sqlite 已经编译为 win / mac,将尝试尽快上传),当尝试在我的节点主文件上使用 fork 方法时,我得到的只是“无法提取包”。跨度>
  • 我正在使用最后一个:0.12.3
  • 我现在就试试这个,希望 sqlite3 可以在 osx 和 windows 上运行以该版本为目标。 (感谢您的快速回复)。
  • 刚刚看到 sqlite3 不会为 nw.js 0.12.3 构建,所以我被锁定到 0.8.6(也许是 0.10),我将不得不很快再试一次,需要应用程序的其他部分目前继续进行。
  • 是的,您只需要使用nw-gyp 即可使其正常工作
猜你喜欢
  • 2017-08-04
  • 2015-01-27
  • 1970-01-01
  • 1970-01-01
  • 2016-09-05
  • 2015-05-05
  • 2023-03-05
  • 1970-01-01
  • 2020-10-24
相关资源
最近更新 更多