PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, August 17, 2022

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

 August 17, 2022     electron, javascript, node.js, output, terminal     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing