从 NodeJS 捕获 bash 输出

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11465907/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 02:44:49  来源:igfitidea点击:

Capturing bash output from NodeJS

bashnode.js

提问by Ahmed Nuaman

Is it possible to start and continue to capture output from a certain bash process with node? For example: say I was run tail /some/file, how can I keep listening to every new line printed and act on the output?

是否可以使用节点启动并继续捕获某个 bash 进程的输出?例如:假设我是 run tail /some/file,我怎样才能继续收听打印的每一行新行并对输出采取行动?

回答by Andrey Sidorov

var spawn = require('child_process').spawn,
    tail  = spawn('tail', ['-f', '/tmp/somefile']);
tail.stdout.pipe(process.stdout);

child_process module is well documented

child_process 模块有据可查

回答by Dominic Barnes

For completeness, I've added this answer as well.

为了完整起见,我也添加了这个答案。

You can use child_process.spawnto spawn a process and monitor it's output. However, for a command like tail, cat, etc that don't run long or continuously you can just use child_process.execand it will capture the entire output for stdoutand stderrand give it to you all at once.

您可以使用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
});