spawning a child process to call npm-installed command in nodejs causes ENOENT in windows

StackOverflow https://stackoverflow.com/questions/19417652

  •  01-07-2022
  •  | 
  •  

Question

I've searched a lot but got no correct answer.

Firstly I'm sure the command is usable under command line, here is the output:

> lessc
lessc: no input files

usage: lessc [option option=parameter ...] <source> [destination]

However when use child_process.spawn, I got:

> node test.js
Encountered error: { [Error: spawn ENOENT] code: 'ENOENT', errno: 'ENOENT', syscall: 'spawn' }

I'm sure the process.env is given to spawn, here is the nodejs code:

var build = require('child_process').spawn(
    'lessc',
    [],
    {
        stdio: 'inherit',
        env: process.env
    }
);

build.on(
    'error',
    function (err) {
        console.log('Encountered error:', err);
        process.exit();
    }
);
build.on(
    'close', 
    function (err) {
        console.log('close');
    }
);

And weiredly, it only encounter ENOENT when the command is installed via npm install -g, it works well on for example dir or del system command

Était-ce utile?

La solution

As is turns out, the following works:

var spawn = require('child_process').spawn;

var b = spawn(
    process.env.comspec,
    ['/c', 'lessc'],
    { stdio: 'inherit' }
);

Note that you don't need to explicitly pass env as you do, the default is to inherit.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top