Run and get shell command output in node.js

In node.js, I would like to find a way to get the output of a Unix terminal command. Is there any way to do this?

function getCommandOutput(commandString){ // now how can I implement this function? // getCommandOutput("ls") should print the terminal output of the shell command "ls" } 
+63
command-line-interface shell
Oct 17 '12 at 18:41
source share
4 answers

The way I do this in the project, I am working now.

 var exec = require('child_process').exec; function execute(command, callback){ exec(command, function(error, stdout, stderr){ callback(stdout); }); }; 

Example: fetching a git user

 module.exports.getGitUser = function(callback){ execute("git config --global user.name", function(name){ execute("git config --global user.email", function(email){ callback({ name: name.replace("\n", ""), email: email.replace("\n", "") }); }); }); }; 
+93
Oct 17 '12 at 18:47
source share

Are you looking for child_process

 var exec = require('child_process').exec; var child; child = exec(command, function (error, stdout, stderr) { console.log('stdout: ' + stdout); console.log('stderr: ' + stderr); if (error !== null) { console.log('exec error: ' + error); } }); 



As already mentioned by Renato, there are now some synchronous exec packages, see sync-exec , which may be more than what I'm looking for. Keep in mind that node.js is designed as a single-threaded high-performance network server, so if you want to use it for use, stay away from sync-exec files, unless you use it at startup or something like that.

+19
Oct 17 '12 at 18:44
source share

If you use the node later than 7.6 and you don’t like the callback style, you can also use the promisify node-util function with async/await to get shell commands that are read cleanly. Here is an example of an accepted answer using this method:

 const { promisify } = require('util'); const exec = promisify(require('child_process').exec) module.exports.getGitUser = async function getGitUser () { const name = await exec('git config --global user.name') const email = await exec('git config --global user.email') return { name, email } }; 

This also has the added benefit of returning a rejected promise for failed commands that can be processed using try/catch inside asynchronous code.

+5
May 14 '18 at 16:30
source share

Thanks to Renato's answer, I created a really simple example:

 const exec = require('child_process').exec exec("git config --global user.name", (err, stdout, stderr) => console.log(stdout)) 
+2
Jul 17 '18 at 13:15
source share



All Articles