7

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?

Duke
  • 145
  • 3
  • 11
  • If I do this `cmd.stderr.toString()`, I can see the error, but **cmd,error** is still undefined... – Duke Oct 20 '16 at 08:56

2 Answers2

9

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;
}
João Pimentel Ferreira
  • 14,289
  • 10
  • 80
  • 109
  • 1
    Just a note, `process.exit` is not recommended. See this [SO answer](https://stackoverflow.com/a/37592669/4017403) before copy-pasting – Anas Tiour Jun 21 '19 at 14:07
0

Fixing some of the issues with a previous answer. Here is how I was able to get it to work properly:

const npmInstall = spawnSync(
  "npm",
  ["install"],
  { stdio: ["inherit", "inherit", "pipe"] }
);

if (npmInstall.stderr.toString().trim()) {
  console.error(`${errorPrefix}${npmInstall.stderr.toString()}`);
} else {
  console.log("NPM Install Complete.");
}
Mike T
  • 513
  • 5
  • 14