简体   繁体   English

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

[英]How to read an output of terminal command line by line in Javascript

I am executing a terminal command and want to read output line by line.我正在执行终端命令并希望逐行读取输出。 Here is my code ;这是我的代码;

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;
    });

Is it possible to read output line by line and how ?是否可以逐行读取输出以及如何读取?

You can split output on the EOL character to get each line as an entry in an array.您可以在 EOL 字符上拆分output ,以将每一行作为数组中的一个条目。 Note that this will create a blank entry after the final EOL character, so if you know that the command ends with that (which it probably does), then you should trim/ignore that last entry.请注意,这将在最后一个 EOL 字符之后创建一个空白条目,因此如果您知道命令以该字符结尾(它可能会这样做),那么您应该修剪/忽略最后一个条目。

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]}`);
  }
});

If your concern is that the output may be very long and you need to start processing it before the command finishes or something like that, then you probably want to use spawn() or something else other than exec() (and perhaps look into streams).如果您担心输出可能很长并且您需要在命令完成或类似的事情之前开始处理它,那么您可能想要使用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());
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM