PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, July 22, 2022

[FIXED] How to use node's child_process.exec() with promises

 July 22, 2022     child-process, exec, node.js     No comments   

Issue

I try to execute long processes sequentially with node.js (docker exec commands).

I do:

const childProcess = require('child_process');

const execWithPromise = async command => {
    return new Promise(async resolve => {
        const process = childProcess.exec(command);

        process.on('exit', err => resolve(err));
        process.on('close', err => resolve(err));
    });
};

const run = async () => {
    await execWithPromise('/usr/local/bin/docker exec -i -t cucumber node long-running-script.js');
    await execWithPromise('/usr/local/bin/docker exec -i -t cucumber node long-running-script.js');
};

run();

But the promise is resolved immediately with a result of 1. In both cases. The command runs on the commandline just fine.

Why is it returning immediately?


Solution

child_process.exec expects a callback as the second or third argument. It doesn't return a promise. You have a few choices depending on your use case and version of node.

Use a callback and return the resolve.

return new Promise(async resolve => {
     childProcess.exec(command, (err, stout, sterr) {
        resolve(err ? sterr : stout)
      }
  });

Use spawn instead (keeping most of your code)

const execWithPromise = async command => {
    return new Promise(async (resolve, reject) => {
        const process = childProcess.spawn(command);
        process.on('data', data => resolve(data));
        process.on('error', err => reject(err));
        process.on('close', err => reject(err));
    });
};

Use execSync with try catch

return new Promise(async (resolve, reject) => {
    try {
        resolve(childProcess.execSync(command));
    } catch(error) {
      reject(error) 
    }
});


Answered By - Peter Grainger
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing