Node.js产生子进程并实时输出终端 [英] Node.js spawn child process and get terminal output live

查看:852
本文介绍了Node.js产生子进程并实时输出终端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个脚本,输出"hi",睡眠一秒钟,输出"hi",睡眠1秒,依此类推.现在我想我可以用这种模型解决这个问题.

I have a script that outputs 'hi', sleeps for a second, outputs 'hi', sleeps for 1 second, and so on and so forth. Now I thought I would be able to tackle this problem with this model.

var spawn = require('child_process').spawn,
temp    = spawn('PATH TO SCRIPT WITH THE ABOVE BEHAVIOUR');

temp.stdout.pipe(process.stdout);

现在的问题是,需要完成任务才能显示输出.据我了解,这是由于新产生的进程接受了执行控制.显然,node.js不支持线程,那么有什么解决方案吗?我的想法是可能运行两个实例,第一个实例用于创建任务的特定目的,并考虑到可以实现的目的,将其通过管道将输出传递给第二个实例的进程.

Now the problem is that the task needs to be finished in order for the output to be displayed. As I am understanding it, this is due to the fact that the newly spawned process takes execution control. Obviously node.js does not support threads so any solutions? My idea was to possibly run two instances, first one for the specific purpose of creating the task and have it pipe the output to process of the second instance, considering this can be achieved.

推荐答案

我仍然对Node.js感兴趣,但是我有一些想法.首先,我相信您需要使用execFile而不是spawnexecFile用于当您具有脚本的路径时,而spawn用于执行Node.js可以针对您的系统路径解析的众所周知的命令.

I'm still getting my feet wet with Node.js, but I have a few ideas. first, I believe you need to use execFile instead of spawn; execFile is for when you have the path to a script, whereas spawn is for executing a well-known command that Node.js can resolve against your system path.

var child = require('child_process').execFile('path/to/script', [ 
    'arg1', 'arg2', 'arg3', 
], function(err, stdout, stderr) { 
    // Node.js will invoke this callback when process terminates.
    console.log(stdout); 
});  

2.将侦听器添加到子进程的标准输出(

2. Add a listener to the child process' stdout stream (9thport.net)

var child = require('child_process').execFile('path/to/script', [ 
    'arg1', 'arg2', 'arg3' ]); 
// use event hooks to provide a callback to execute when data are available: 
child.stdout.on('data', function(data) {
    console.log(data.toString()); 
});

此外,似乎存在一些选项,您可以从其中将生成的进程与Node的控制终端分离,这将使其可以异步运行.我尚未对此进行测试,但是 API文档中有一些示例像这样:

Further, there appear to be options whereby you can detach the spawned process from Node's controlling terminal, which would allow it to run asynchronously. I haven't tested this yet, but there are examples in the API docs that go something like this:

child = require('child_process').execFile('path/to/script', [ 
    'arg1', 'arg2', 'arg3', 
], { 
    // detachment and ignored stdin are the key here: 
    detached: true, 
    stdio: [ 'ignore', 1, 2 ]
}); 
// and unref() somehow disentangles the child's event loop from the parent's: 
child.unref(); 
child.stdout.on('data', function(data) {
    console.log(data.toString()); 
});

这篇关于Node.js产生子进程并实时输出终端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆