如何在 silent/not_silent 模式下在 Node 中生成分离命令?

How to spawn detached command in Node in silent/not_silent mode?

我正在为我的节点项目制作自动化脚本,但遇到了一些我无法解决的小问题。

我想使用 grunt 任务启动 3 个独立进程:selenium-standalone start 用于测试,mongod --dbpath ./mongonode app.js。 我对所有这些都使用类似的代码

var spawn = require('child_process').spawn,
command = 'selenium-standalone.cmd', // or "mongod" or "node"
args = ['start']; // or ["--dbpath", path.join(process.cwd() + "/mongo/")] or ['app.js']
var ch = spawn(command, args, {
                detached: true,
                env: process.env,
                stdio: 'ignore'
            });
ch.unref();

所有进程在后台成功启动,但行为不同。 Selenium 打开新终端 window,所以我可以看到它做了什么,我可以按双 ctrl+C 关闭它。但是 mongod --dbpath ./mongonode app.js 是静默启动的。它们可以工作,我可以在任务管理器中找到它们(或通过 ps *mongod*)。

所以,我的问题是:我怎样才能影响这种行为?我想统一它并使用一些外部配置参数来统治它。

我在 Windows 10.

上使用节点

谢谢。

我找到的解决方法:

// This one will close terminal window automatically.
// all output will be in terminal window
spawn("cmd", ["/k", "node", options.appFile], {
                    detached: true,
                    stdio: 'inherit'
                }).unref(); 

// This one will NOT close terminal window automatically after proccess ends his job
// for some reason `spawn('start', [...])` will failed with ENOENT
spawn("cmd", ["/c", "start", "cmd", '/k', "node", options.appFilePath], {
                detached: true,
                stdio: 'inherit'
            }).unref(); 

// This is freak one. All output will go to the file. 
// New terminal window will not be opened
spawn("cmd", ["/c", "start", "cmd", '/k', "node", options.appFilePath, options.logFilePath,"2>&1"], {
                detached: true,
                stdio: 'inherit'
            }).unref();

// This one is better than previous. Same result
var out = fs.openSync(options.logFilePath, 'a'),
    stdioArgs = ['ignore', out, out];
spawn("node", [options.appFilePath], {
            detached: true,
            stdio: stdioArgs
        }).unref(); 

希望有人会觉得有用。