Skip to content

Instantly share code, notes, and snippets.

@wimarbueno
Forked from myconode/spawnSync_example.js
Created January 10, 2023 22:06
Show Gist options
  • Save wimarbueno/584b4b839af8819d6842b1a89cf1d9d7 to your computer and use it in GitHub Desktop.
Save wimarbueno/584b4b839af8819d6842b1a89cf1d9d7 to your computer and use it in GitHub Desktop.
Example use of spawnSync
'use strict'
// https://nodejs.org/api/child_process.html#child_process_child_process_spawnsync_command_args_options
const spawn = require('child_process').spawnSync
// object returned when process has completely exited
const child = spawn('which', ['node'] )
// view status
console.log( child.status )
// view output (stdout & stderr combined)
// must convert buffer to string
console.log (child.output.toString('utf8') )
// e.g. function that uses spawnSync
// which: displays user path to specified binary
// @param command
// @return object
function which(cmd){
return spawn('which', [cmd])
}
console.log( which('npm').stdout.toString('utf8') )
// piping
console.log(
"NODE PROCESSES: " +
spawn('grep', ['node'], { input: spawn('ps', ['aux'] ).stdout })
.stdout.toString('utf8')
)
process.on('exit', function() { console.log('bye') } )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment