javascript - 如何在Javascript中逐行读取终端命令行的输出

标签 javascript node.js terminal electron output

我正在执行终端命令,想逐行读取输出。
这是我的代码;

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/

相关文章:

javascript - 是否可以使用 C# 从使用 Javascript 动态添加的行中获取值?

javascript - 如何用javascript做到这一点?它就像一个开关,但我似乎没有找到开关功能

javascript - 有没有办法在 Javascript 中正确地乘以两个 32 位整数?

node.js - 使用 docker 时,npm 库不工作

javascript - 在 node.js 中调用多个异步函数的正确过程

javascript - 未捕获的类型错误 : Cannot read property 'ca' of null when dragging Google Map

node.js - 使用 Cheerio 抓取时出现问题

java - 通过终端运行 Java 代码时出现问题

php - 如果我从 MAMP 安装 mysql,如何运行它

Linux下C关闭然后打开标准输入