Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

nodejs 如何执行 shell 命令,并把结果实时回显输出?

nodejs 如何执行 shell 命令,并把结果实时回显输出

const exec = require('child_process').exec;

exec('shell 命令', (error, stdout, stderr) => {
        console.log({ error, stdout, stderr });
    });

我尝试如上写法
但是发现回调函数 (error, stdout, stderr)=>{} 在命令执行完毕才一次性返回, 而不是实时回显

请问如何让输出实时回显


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

你需要用 spawn, 它是一个事件触发器对象版本的 exec, 以下例子来自 node 官方文档:

https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options

const { spawn } = require('child_process');
const ls = spawn('ls', ['-lh', '/usr']);

ls.stdout.on('data', (data) => {
  console.log(`stdout: ${data}`);
});

ls.stderr.on('data', (data) => {
  console.error(`stderr: ${data}`);
});

ls.on('close', (code) => {
  console.log(`child process exited with code ${code}`);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.7k users

...