简体   繁体   中英

/bin/sh: 1: node: not found with child_process.exec

I tried to run a nodejs script with the built in child_process module and it works fine until i give it options. Specially when i add the env property to the options object.

let exec = require('child_process').exec;

exec('node random.js', { env: {} }, (err) => {
  console.log(err);
})

Then i get this error: /bin/sh: 1: node: not found .

I have node installed with nvm, maybe that is the cause, but don't know why.

If you exec a new shell from your script this don't have the same environment of the parent shell (your script).

So you have to provide all the needed environment.

In your case I see 2 way you could do.

First: you create a node command with the full path:

let exec = require('child_process').exec;

let node_cmd = '/path/to/my/node/node';

exec(node_cmd + ' random.js', { env: {} }, (err) => {
  console.log(err);
});

So you could use env variables to handle the path, or just change it when you need.

Second, pass the path variable to the command:

let exec = require('child_process').exec;

let env_variables = 'PATH='+process.env.PATH;

let cmd = env_variables + ' node random.js';

exec(cmd, { env: {} }, (err) => {
  console.log(err);
});

Another way is using the dotenv package.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM