Search code examples
javascriptnode.jspromisecallbackchild-process

How to wait for node exec response?


how can I use a callback tor a promise correctly to get the result from a node exec in the condole.log() function?

import { exec } from 'child_process';
const check = () => {
    exec(`...`, (err, stdout) => {
        if (err) {
         return false         
        }
        else {
         return true
        }
    })
}
console.log(check()) // getting undefined

I've tried using .on('exit') but none worked... would love to get some help here. THANKS!!


Solution

  • You can either use the Promise constructor to do it yourself or you can use the util module to convert a callback invoking function into one that returns a promise

    Using the util module

    const util = require("util");
    const exec = util.promisify(require("child_process").exec);
    
    const check = async () => {
      const output = await exec(`echo hi`);
    
      console.log(output);
    };
    
    check();
    

    Wrapping with the Promise constructor

    import { exec } from "child_process";
    const check = async () => {
      return new Promise((resolve, reject) => {
        exec(`echo hi`, (err, stdout) => {
          if (err) {
            reject(err);
          } else {
            resolve(stdout);
          }
        });
      });
    };