Last active
October 25, 2022 00:25
-
-
Save miguelmota/e8fda506b764671745852c940cac4adb to your computer and use it in GitHub Desktop.
Node.js run command in child process as Promise example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
})() |
easy, thank you. :-)
You should reject instead of resolving to false.
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();
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);
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
Thanks so much, clear example and you saved my day 💯