Skip to content

Instantly share code, notes, and snippets.

@miguelmota
Last active October 25, 2022 00:25
Show Gist options
  • Save miguelmota/e8fda506b764671745852c940cac4adb to your computer and use it in GitHub Desktop.
Save miguelmota/e8fda506b764671745852c940cac4adb to your computer and use it in GitHub Desktop.
Node.js run command in child process as Promise example
const { exec } = require('child_process')
function run(cmd) {
return new Promise((resolve, reject) => {
exec(cmd, (error, stdout, stderr) => {
if (error) return reject(error)
if (stderr) return reject(stderr)
resolve(stdout)
})
})
}
// usage example
;(async () => {
const result = await run('echo "hello"')
console.log(result) // hello
})()
@m00zi
Copy link

m00zi commented May 31, 2018

Thanks so much, clear example and you saved my day 💯

@audstanley
Copy link

easy, thank you. :-)

@ArcticZeroo
Copy link

You should reject instead of resolving to false.

@rjcorwin
Copy link

rjcorwin commented Jul 26, 2018

Here is an example from the docs: https://nodejs.org/api/child_process.html

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

async function lsExample() {
  const { stdout, stderr } = await exec('ls');
  console.log('stdout:', stdout);
  console.log('stderr:', stderr);
}
lsExample();

@JESUSrosetolife
Copy link

JESUSrosetolife commented Dec 22, 2021

Here's an example that uses ECMAScript modules/import instead of require:

import util from 'util';
import { exec as execNonPromise } from 'child_process';
const exec = util.promisify(execNonPromise);

const command = 'echo 123';
const { stdout, stderr } = await exec(command);
console.log('stdout:', stdout);
console.log('stderr:', stderr);

@drobati
Copy link

drobati commented Oct 25, 2022

I could not pass options to a util.promisify exec. I needed maxBuffer in the options. I believe the original answer is probably what I'll use, with modifications. https://nodejs.org/api/child_process.html#child_processexeccommand-options-callback

const { exec } = require('child_process')

function run(cmd, options) {
  return new Promise((resolve, reject) => {
    exec(cmd, options, (error, stdout, stderr) => {
      if (error) return reject(error)
      if (stderr) return reject(stderr)
      resolve(stdout)
    })
  })
}

// usage example
;(async () => {
  const result = await run('echo "hello"', { maxBuffer: 1024 * 1024 * 2 })
  console.log(result) // hello
})()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment