newbiedev
newbiedev

Reputation: 3586

nodejs child process - Error: spawn node ENOENT

I'm using this code to try spawn a child process that needs to run a script.

const child = require('child_process').spawn;
const path = require('path');
const script = path.format({dir: __dirname, base: 'myscript.js'});

    child('node', [script], {
        cwd: __dirname,
        env: {
            TEST_USERNAME: 'myuser',
            TEST_PASSWORD: 'mypassword'
        }
    }).on('error', (error) => {
        console.log(error);
    });

I'm getting this error when I try to run my index.js script

Error: spawn node ENOENT
    at Process.ChildProcess._handle.onexit (node:internal/child_process:276:19)
    at onErrorNT (node:internal/child_process:476:16)
    at processTicksAndRejections (node:internal/process/task_queues:80:21) {
  errno: -2,
  code: 'ENOENT',
  syscall: 'spawn node',
  path: 'node',
  spawnargs: [ '/Users/dev/Desktop/cli-training/demo.js' ]
}

UPDATE

I'm trying to run the child script after that inquirer.js have prompted some questions to the user. Can be this the problem?I've noticed that the child process will be not executed. Inside my child script I have this code

const { IgApiClient } = require('instagram-private-api');
const chalk = require('chalk');

console.log(chalk.magenta('Starting child script'));

const ig = new IgApiClient();

console.log(process.argv);

How I can fix it?

Upvotes: 5

Views: 18351

Answers (1)

Jerome
Jerome

Reputation: 354

If you want to execute the node binary in a child-process, it s better to refer to its full path, you can find it with process.execPath

this should fix your problem

child(process.execPath, [script], {
        cwd: __dirname,
        env: {
            TEST_USERNAME: 'myuser',
            TEST_PASSWORD: 'mypassword'
        }
    }).on('error', (error) => {
        console.log(error);
    });

Upvotes: 3

Related Questions