How to get the output of a child process in Node.JS?

First of all, I am a complete noob and started using Node.JS yesterday (this was my first time I used Linux in years), so please be beautiful and explicit

I am currently creating a Node.JS program that should, among other things, run shell commands (basically: mount a USB drive). I am currently using

var spawn = require('child_process').spawnSync; function shspawn(command) { spawn('sh', ['-c', command], { stdio: 'inherit' }); } shspawn('echo Hello world'); shspawn('mkdir newdir'); 

etc .. this is a really convenient way to do this for me. The problem is that I would like to save the output, for example, the "ls" command in a variable, like

 var result = shspawn('ls -l') 

I read a few examples on the Internet, but they rarely use spawn, and when they do this, it doesnโ€™t work for me (I think I can do something wrong, but again I am a noob in Node)

If you have an idea better than using child_process_spawnSync, I am open to any idea, but I would like to keep my program as long as possible without packages :)

EDIT: I need it to work synchronously! This is why I started using spawnSync. I will use some commands, such as dd, which take time and must be completed completely before the program moves to another command.

+5
source share
1 answer

You can do something like below.

  var spawn = require('child_process').spawn; // Create a child process var child = spawn('ls' , ['-l']); child.stdout.on('data', function (data) { console.log('ls command output: ' + data); }); child.stderr.on('data', function (data) { //throw errors console.log('stderr: ' + data); }); child.on('close', function (code) { console.log('child process exited with code ' + code); }); 

Update: using spawnSync

  var spawn = require('child_process').spawnSync; var child = spawn('ls' , ['-l','/usr']); console.log('stdout here: \n' + child.stdout); 
+5
source

All Articles