Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 338
Joshua Comeau Avatar asked Jun 02 '18 22:06

Joshua Comeau


1 Answers

You can override the PORT even without passing env, using /usr/bin/env

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

If you haven't checked process.env, make sure you override PATH with a known-good value.

const child = childProcess.spawn('npm', ['run', taskName], {
  cwd: `${parentPath}/${projectId}`,
  env: {
    PATH: '/bin:/usr/bin:/usr/local/bin',
    PORT: 4545,
  }
});
like image 89
Charles Duffy Avatar answered Nov 09 '22 11:11

Charles Duffy