Node.js 使用nodejs实时输出进度
当我在命令行上运行Node.js 使用nodejs实时输出进度,node.js,Node.js,当我在命令行上运行npm run react build命令时,它会显示生成过程中的进度,但当我在命令行中使用nodejs运行同一命令时,它会首先生成,然后显示整个输出 如何使脚本在处理过程中显示进度 // index.js try { await execShellCommand("npm run react-build"); }catch(error) { console.error(error) } function execShellCommand(cmd) { c
npm run react build
命令时,它会显示生成过程中的进度,但当我在命令行中使用nodejs运行同一命令时,它会首先生成,然后显示整个输出
如何使脚本在处理过程中显示进度
// index.js
try {
await execShellCommand("npm run react-build");
}catch(error) {
console.error(error)
}
function execShellCommand(cmd) {
const exec = require("child_process").exec;
return new Promise((resolve, reject) => {
exec(cmd, (error, stdout, stderr) => {
if (error) {
console.warn(error);
return reject(error);
}
console.info(stdout);
console.info(stderr);
resolve(stdout ? stdout : stderr);
});
});
}
发生这种情况的原因是,当您在shell中运行命令时,您使用的是交互式shell,但当您使用exec时,您正在执行该命令,并且仅当它完成获取输出时 您可以使用exec而不是exec
正如在参数上看到的,您可以订阅事件,而不是返回结果,例如stdout,它还有一个
shell
选项,您应该将该选项设置为true,以获得相同的交互行为您正在缓冲来自stdout\stderr的日志,而不是流式传输日志。根据exec
:
生成一个shell,然后在该shell中执行命令,缓冲任何生成的输出
也就是说,它会等待命令完成,然后才使用它收集的所有stdout\stderr调用回调
我认为您应该研究一下spawn
命令。根据spawn
您将从stdout\stderr获得一个数据流:
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}`);
});
注意:尽管如此,它不能保证正确显示进度条。因为这些进度条在VT100控制序列上高度相关,我不确定Node.js将如何在这些流中处理它们