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

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.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Parvez Alam

Hey, I am Parvez Alam. A software developer since 2009. I love learning and sharing knowledge. https://www.phpflow.com/