Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

/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.

like image 420
VuesomeDev Avatar asked Dec 29 '25 09:12

VuesomeDev


1 Answers

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.

like image 198
Mario Santini Avatar answered Dec 31 '25 00:12

Mario Santini