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?
ENV
containsPWD
, so it can be confused forspawn
when you provides otherPWD
inENV
(it's__dirname
of executed Node file) thanCWD
inspawn
. – CrackbrainedparentPath
in this case usesos.homeDir()
to get an absolute path to that directory (the variable name is confusing, sorry about that!) – Bekerwhich npm
, but with__dirname
instead${parentPath}/${projectId}
) and it is working for me. I tested with Node v6.11.4 and v10.3.0. So probably the case is about something around this code. Could you replace this path with__dirname
? Could you console.log${parentPath}/${projectId}
and show me the result? – Crackbrained__dirname
, same result. It gives me the result regardless of what the command is. even spawningls
without arguments or acwd
throws the same error,spawn ls ENOENT
. The logged path is/Users/joshuacomeau/work/guppy-projects/hello-world
– Beker/usr/bin/npm
, for example (correcting for the real location). If that fails, then you're likely sandboxed (be it via SELinux constraints, or a chroot jail, or something else). – Picaresque/usr/bin/printenv
to look at your actual environment, including the PATH, and get a more solid look at what's going on (maybe editing what that finds into the question). Or take the advice in my answer and use/usr/bin/env
to set thePORT
variable without changing anything else. :) – Picaresque