Monday 16 July 2018

childProcess.spawn fails when `env` is specified

I'm using Node's childProcess module to try and run NPM tasks.

When I do the following, everything works file:

  const child = childProcess.spawn('npm', ['run', taskName], {
    cwd: `${parentPath}/${projectId}`,
  });

However, I need to provide environment variables for the command to succeed. I tried using the env argument, like so:

  const child = childProcess.spawn('npm', ['run', taskName], {
    cwd: `${parentPath}/${projectId}`,
    env: {
      ...process.env,
      PORT: 4545,
    }
  });

When I do this, I get the following error: Uncaught Error: spawn npm ENOENT.

It turns out, I get this error regardless of what the env value is, and regardless of what the command is. For example:

  const child = childProcess.spawn('which', ['npm'], {
    cwd: `${parentPath}/${projectId}`,
    env: process.env,
  });

This code fails with Uncaught Error: spawn which ENOENT. In other words, when any value is set to env, then the spawned process fails since even built-in commands like which are unknown.

EDIT: maybe worth mentioning that I'm using Electron. I know Electron somehow fuses Node and Chromium, so maybe it's some quirk with that?



from childProcess.spawn fails when `env` is specified

No comments:

Post a Comment