This tutorial will show you how to run shell/window commands from within a nodejs application.The module child_process.exec is specifically designed for executing shell scripts into nodejs applications.
The child_process
module launches a shell then executes the command within that shell, buffering any generated output. The shell directly processes the command string passed to the exec function. We can use stdin
, stdout
and stderr
within our NodeJS application.
The syntax of exec –
child_process.exec(command[, options][, callback]);
The above method return the instance of
Whereas :
- command : The command to run, with space-separated arguments
- options : This is the optional argument that ll contain cwd, encoding, uid, gaid etc.You can get more information from here.
There are following callback method will be called with the output when the process terminates –
-
error
The error objects are thrown when run-time errors occur. -
stdout
string | Buffer -
stderr
string | Buffer
How to run Shell Command in Nodejs
We can use the exec
function to run a wide range of windows and Unix commands and also pass any number of arguments –
const { exec} = require('child_process'); const child = exec('ls', ['-lh', '/usr']); console.log('error', child.error); console.log('stdout ', child.stdout); console.log('stderr ', child.stderr);
We can also capture the output using callback method.
Exec command Using Promise
We can also run shell command and resolve promise as like below –
function execShellCommand(cmd) { const exec = require("child_process").exec; return new Promise((resolve, reject) => { exec(cmd, { maxBuffer: 1024 * 500 }, (error, stdout, stderr) => { if (error) { console.warn(error); } else if (stdout) { console.log(stdout); } else { console.log(stderr); } resolve(stdout ? true : false); }); }); }
Conclusion
Nodejs helps in the execution of commands via the child process. This aids in the removal of shell scripting dependencies. You can write a shell script that helps in the automation of infrastructure or processes.
I hope you found this tutorial helpful; if you have any questions, please leave them in the comments section below!.