Issue
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 ?
Solution
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());
});
Answered By - Trott Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.