SoniCoder
SoniCoder

Reputation: 4174

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

Upvotes: 3

Views: 8516

Answers (1)

Mario Santini
Mario Santini

Reputation: 3003

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.

Upvotes: 4

Related Questions