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