1

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 ?

1 Answer 1

1

You can split output on the EOL character to get each line as an entry in an array. 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.

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).

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());
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.