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
})()
@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