Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle Node.js spawnSync errors

I'm trying to run "npm publish" from a gulp task. It works, but I want to handle any error that npm command itself throws.

If I execute this code:

var cmd = spawnSync('npm.cmd', ['publish', packageDir], { stdio: 'inherit' })

cmd.stdout and cmd.stderr are null. If I execute

var cmd = spawnSync('npm.cmd', ['publish', packageDir], { stdio: 'pipe' })

cmd.stdout and cmd.stderr are buffers, like <Buffer 6e 70 6d 20 45 52...

What am I missing here?

like image 470
Duke Avatar asked Oct 20 '16 08:10

Duke


1 Answers

In Node documentation regarding options.stdio it says

By default, the child's stdin, stdout, and stderr are redirected to corresponding subprocess.stdin, subprocess.stdout, and subprocess.stderr.

In your options use

{ stdio: ['inherit', 'inherit', 'pipe'] }

And then check for stderr. An example:

var spawn = childProcess.spawnSync('node myScript.js', { stdio: ['inherit', 'inherit', 'pipe'] })

if (spawn.stderr) {
  console.log(Error(spawn.stderr))
  process.exitCode = 1;
}
like image 176
João Pimentel Ferreira Avatar answered Nov 07 '22 18:11

João Pimentel Ferreira