Categories
JavaScript Answers

How to promisify Node’s child_process.exec and child_process.execFile functions with Node.js Bluebird?

Spread the love

To promisify Node’s child_process.exec and child_process.execFile functions with Node.js Bluebird, we use the util.promisfy method.

For instance, we write

const util = require("util");
const exec = util.promisify(require("child_process").exec);

const run = async () => {
  try {
    const { stdout, stderr } = await exec("ls");
    console.log("stdout:", stdout);
    console.log("stderr:", stderr);
  } catch (e) {
    console.error(e);
  }
};

to call util.promisify with the child_process module’s exec method to convert it to return a promise.

Then we define the run function that calls exec to run a command.

It returns a promise, so we await to get an object with the stdout and stderr outputs.

This works with Node.js 10 or later.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *