node.jschild-processspawn

How to use promisify() with the spawn() function for the 'child_process'?


I have the following code example, and I have now ideas on how to resolve this using utils.promisify(); ONLY! Not Promise!

const spawn = child_process.spawn('docker', ['--version']);

spawn.stdout.on('data', (data) => {
   process.stdout.write(data);
});

spawn.on('error', () => {
   process.stderr.write(error);
   process.exit(1);
});

The second code example works fine.

const promisifiedExecFile = promisify(child_process.execFile);

async function test() {
  const version = await promisifiedExecFile('docker', ['--version']);
  console.log(version);
}

test();

Solution

  • Node.js' built-in util package has a promisify() function that converts callback-based functions to promise-based functions. This lets you use promise chaining and async/await with callback-based APIs.

    I think that we can't use the promisify() with the spawn() function. For example we can use promisify() with execFile() instead of spawn():

    async asyncExecFile(tool) {
            const execFile = util.promisify(child_process.execFile);
    
            return await execFile(tool, ['--version'])
                .catch(() => {
                    this.printError(`The "${tool}" don't exist in the current environment. \n`);
                    process.exit(0);
                });
    }