捕获NodeJS的bash输出
是否有可能开始并继续捕获某个bash进程的输出与节点? 例如:说我正在运行tail /some/file
,我怎样才能不断地收听每一行新的行,并在输出上行动?
为了完整性,我也添加了这个答案。
你可以使用child_process.spawn
产生一个进程并监视它的输出。 但是,对于像tail,cat等那样不能长时间运行的命令,只需要使用child_process.exec
,它会捕获stdout
和stderr
的全部输出,并一次性提供给你。
var cp = require("child_process"); cp.exec("tail /some/file", function (err, stdout, stderr) { // If an error occurred, err will contain that error object // The output for the command itself is held in stdout and stderr vars });
var spawn = require('child_process').spawn, tail = spawn('tail', ['-f', '/tmp/somefile']); tail.stdout.pipe(process.stdout);
child_process模块是有据可查的