简体   繁体   English

如何在单独的 cmd 窗口或终端中启动 nodejs 子进程

[英]How to start a nodejs child process in separate cmd window or terminal

I want to start a nodejs child process in a separate console window rather than of listening to its data event.我想在单独的控制台窗口中启动一个 nodejs 子进程,而不是监听它的数据事件。

as per the Documentation根据文档

with the detached option, the child supposes to have its own console window but it's not happening.使用分离选项,孩子应该有自己的控制台窗口,但它没有发生。

my code in main.js我在 main.js 中的代码

const { spawn} = require("child_process");

var child = spawn("node", ["./count.js"], {
    detached: true,
    stdio: 'ignore'
});

in the count.js file, I have在 count.js 文件中,我有

console.log(`running in child process with PID ${process.pid})

The only solution I've found to work on windows 10 is to spawn a separate cmd.exe process entirely:我发现在 Windows 10 上工作的唯一解决方案是完全生成一个单独的 cmd.exe 进程:

const { spawn} = require("child_process");

var child = spawn("cmd.exe", ["/c", "node", "count.js"], {
    detached: true,
    stdio: 'ignore'
});

Also be sure to add some delay to your child process so it doesn't quit before you can see it:还要确保为您的子进程添加一些延迟,这样它就不会在您看到它之前退出:

console.log(`running in child process with PID ${process.pid}`);

// wait 5 seconds before closing
setTimeout(() => true, 5000);

And finally, if you want your child window to be entirely independent from the parent (stays open even when the parent closes), you should unref it after you spawn it:最后,如果您希望您的子窗口完全独立于父窗口(即使父窗口关闭也保持打开状态),您应该在生成它后取消引用它:

child.unref();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM