How to execute shell commands synchronously in Node.js?

Published October 27, 2020

To execute shell commands synchronously from Node.js, you can use the execSync() function from the child_process module in Node.js.

// import exec method from child_process module
const { execSync } = require("child_process");

// execute mkdir command synchronously
// to make a directory with name hello
execSync("mkdir hello");

The execSync() function will block the entire operation and waits for the execution of the command. Thus it may not be good to use if this is used with some client-facing applications. Instead, if you want asynchronous execution of command see executing commands asynchronously.

The exec() takes 1 required argument, and 1 optional argument:

  • 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 directory
    • env: to set the environment variable
    • timeout: 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.
  • The function returns the stdout of the command. It will be of type buffer or string.

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 execSync() 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 { execSync } = require("child_process");

// execute touch command synchronously
// to create three text file
const stdout = execSync("touch hello1.txt hello2.txt hello3.txt");

console.log(stdout); // stdout of the command if any

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 { execSync } = require("child_process");

// execute touch command synchronously
// to create three text file
const stdout = execSync("touch hello1.txt hello2.txt hello3.txt", {
  env: {
    NODE_ENV: "production",
  },
});

console.log(stdout); // stdout of the command if any

Now the stdout of the command will be returned from the function and will be held by the variable stdout.

// import exec method from child_process module
const { execSync } = require("child_process");

// execute touch command synchronously
// to create three text file
const stdout = execSync("touch hello1.txt hello2.txt hello3.txt", {
  // setting fake environment variable 😁
  env: {
    NODE_ENV: "production",
  },
});

console.log(stdout); // stdout of the command if any

Now those three txt files will be created. 😃

See this example live in repl.it.

Feel free to share if you found this useful 😃.


Share on: Facebook Twitter