如何为child_processspawn()调用的输出的每一行添加文本前缀?
我使用spawn()from执行多个进程child_process。
const { spawn } = require('child_process');
spawn("sh", ["script1.sh"], { shell: false, stdio: "inherit"});
spawn("sh", ["script2.sh"], { shell: false, stdio: "inherit"});
spawn("sh", ["script3.sh"], { shell: false, stdio: "inherit"});
问题:如何为脚本的输出添加文本前缀?
这个想法是我将能够轻松区分每个脚本记录的内容。
我浏览了spawn文档,但找不到任何有助于实现这一目标的内容。
注意:我无法修改脚本。
回答
您已stdio设置为"inherit"。
如果您将其设置为"pipe",Node.js 将为您提供和 的可读流,您可以使用它来添加前缀。stderrstdin
const { spawn } = require('child_process');
const one = spawn("sh", ["script1.sh"], { shell: false, stdio: "pipe"});
let oneStdout = ''
one.stdout.on('data', function (chunk) {
oneStdout += chunk
const lines = oneStdout.split('n')
while(lines.length > 1) {
const line = lines.shift()
console.log('one',line)
}
oneStdout = lines.shift()
})
one.stdout.on('end', function () {
console.log('one', oneStdout)
})
这是文档中的相关部分:https : //nodejs.org/api/child_process.html#child_process_subprocess_stdio
潜在的陷阱:
在“添加前缀”时,您可能希望为每个新行添加前缀,但并非所有脚本一次都将整行写入标准输出。使用一些echo -n "foobar"在整个输出中使用的脚本来测试您是否正确处理了换行符。
THE END
二维码