我正在执行终端命令,想逐行读取输出。
这是我的代码;
async function executeCommand(command, callback) {
const exec = require('child_process').exec;
await exec(command, (error, stdout, stderr) => {
callback(stdout);
});
};executeCommand("instruments -s devices", (output) => {
//read output line by line;
});
是否可以逐行读取输出以及如何读取?
最佳答案
您可以在EOL字符上分割output
,以获取每一行作为数组中的一项。请注意,这将在最后一个EOL字符之后创建一个空白条目,因此,如果您知道该命令以该结尾(可能这样做),则应 trim/忽略该最后一个条目。
function executeCommand(command, callback) {
const exec = require('child_process').exec;
return exec(command, (error, stdout, stderr) => {
callback(stdout);
});
}
executeCommand('ls -l', (output) => {
const lines = output.split(require('os').EOL);
if (lines[lines.length - 1] === '') {
lines.pop();
}
for (let i = 0; i < lines.length; i++) {
console.log(`Line ${i}: ${lines[i]}`);
}
});
如果您担心输出可能很长,并且您需要在命令完成之前开始处理它或类似的事情,那么您可能想要使用spawn()
或exec()
以外的其他东西(并可能查看流)。function executeCommand(command, args, listener) {
const spawn = require('child_process').spawn;
const subprocess = spawn(command, args);
subprocess.stdout.on('data', listener);
subprocess.on('error', (err) => {
console.error(`Failed to start subprocess: ${err}`);
});
}
executeCommand('ls', ['-l'], (output) => {
console.log(output.toString());
});
关于javascript - 如何在Javascript中逐行读取终端命令行的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64058054/