How To Execute Shell Command in Nodejs
This tutorial help to execute shell/window command into nodejs application.The Node.js
is providing a module child_process.exec which is specifically designed for executing shell scripts into nodejs application.
The child_process module spawns a shell then executes the command within that shell, buffering any generated output. The command string passed to the exec function is processed directly by the shell.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 , The ChildProcess class are EventEmitters that represent spawned child processes.
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 -
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 -
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 -
Conclusion
The nodejs help to execute command using child process.This help to remove dependencies from shell scripting.You can do something as like shell script, that help in automation of infrastructure or process.
I hope you found this tutorial useful, if you need anything further explained then please feel free to reach out to me in the comments section below!
Originally published at https://www.js-tutorials.com on September 19, 2020.