To execute shell commands from Node.js, you can use the exec()
function from the child_process
module in Node.js. The execution of the exec()
function is asynchronous.
// import exec method from child_process module
const { exec } = require("child_process");
// execute mkdir command asynchronously
// to make a directory with name hello
exec("mkdir hello");
The exec()
takes 1 required argument, and 2 optional arguments:
- The command to run on the shell as the first argument. It should be of type
string
(Required). - Options while executing the command. It should be of type
object
(Optional).cwd
: to set the current working directoryenv
: to set the environment variabletimeout
: to set the maximum time for the command to run. etc. are some of the options available. To see more options see Node.js exec() method options.
- A callback function to execute when the process terminates (Optional).
- It is supplied with an
Error
object as the first parameter if there is an error. - It is supplied with an output from the
stdout
as the second parameter. - it supplied with a
stderr
as the third parameter.
- It is supplied with an
Let's say we have to make three files called hello1.txt
, hello2.txt
, and hello3.txt
from a Node.js process.
let's make use of the exec()
function and pass the string touch hello1.txt hello2.txt hello3.txt
to make three txt
files like this,
// import exec method from child_process module
const { exec } = require("child_process");
// execute touch command
// to create three text file
exec("touch hello1.txt hello2.txt hello3.txt");
Now let's set some fake environment variables by passing objects with the env
property as the second argument.
// import exec method from child_process module
const { exec } = require("child_process");
// execute touch command
// to create three text file
exec("touch hello1.txt hello2.txt hello3.txt", {
env: {
NODE_ENV: "production",
},
});
Also, let's make sure that that the output is logged to the console by passing a callback function as the third parameter to the function.
// import exec method from child_process module
const { exec } = require("child_process");
// execute touch command
// to create three text file
exec(
"touch hello1.txt hello2.txt hello3.txt",
{
// setting fake environment variable 😁
env: {
NODE_ENV: "production",
},
},
(error, stdout, stderror) => {
// if any error while executing
if (error) {
console.error("Error: ", error);
return;
}
console.log(stdout); // output from stdout
console.error(stderror); // std errors
}
);
Now those three txt
files will be created. 😃
See this example live in repl.it.