执行:显示标准输出“live"; [英] Exec : display stdout "live"
问题描述
我有这个简单的脚本:
var exec = require('child_process').exec;
exec('coffee -cw my_file.coffee', function(error, stdout, stderr) {
console.log(stdout);
});
我只是执行一个命令来编译一个咖啡脚本文件.但是 stdout 永远不会显示在控制台中,因为命令永远不会结束(因为咖啡的 -w 选项).如果我直接从控制台执行命令,我会收到这样的消息:
where I simply execute a command to compile a coffee-script file. But stdout never get displayed in the console, because the command never ends (because of the -w option of coffee). If I execute the command directly from the console I get message like this :
18:05:59 - compiled my_file.coffee
我的问题是:是否可以使用 node.js exec 显示这些消息?如果是怎么办?!
My question is : is it possible to display these messages with the node.js exec ? If yes how ? !
谢谢
推荐答案
不要使用 exec
.使用 spawn
这是一个 EventEmmiter
对象.然后你可以监听 stdout
/stderr
事件 (spawn.stdout.on('data',callback..)
) as他们发生了.
Don't use exec
. Use spawn
which is an EventEmmiter
object. Then you can listen to stdout
/stderr
events (spawn.stdout.on('data',callback..)
) as they happen.
来自 NodeJS 文档:
From NodeJS documentation:
var spawn = require('child_process').spawn,
ls = spawn('ls', ['-lh', '/usr']);
ls.stdout.on('data', function (data) {
console.log('stdout: ' + data.toString());
});
ls.stderr.on('data', function (data) {
console.log('stderr: ' + data.toString());
});
ls.on('exit', function (code) {
console.log('child process exited with code ' + code.toString());
});
exec
缓冲输出,通常在命令执行完成后返回.
exec
buffers the output and usually returns it when the command has finished executing.
这篇关于执行:显示标准输出“live";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!