Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node spawn child process not working in windows

I have a simple script setup using spawn on windows and its output is:

spawn error: Error: spawn dir ENOENT
spawn child process closed with code -4058

Here's the code:

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

const spawnTest = (() => {
  const dir = spawn('dir');

  dir.stdout.on('data', (data) => {
    console.log(`spawn stdout: ${data}`);
  });

  dir.stderr.on('data', (data) => {
    console.log(`spawn stderr: ${data}`);
  });

  dir.on('error', (code) => {
    console.log(`spawn error: ${code}`);
  });

  dir.on('close', (code) => {
    console.log(`spawn child process closed with code ${code}`);
  });

  dir.on('exit', (code) => {
    console.log(`spawn child process exited with code ${code}`);
  });
})();
like image 987
CoryDorning Avatar asked Aug 02 '26 19:08

CoryDorning


1 Answers

You need the shell: true option for spawn() as in spawn('dir', {shell: true});.

This code works as expected on Windows:

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

const spawnTest = (() => {
  const dir = spawn('dir', {shell: true});       // <== shell: true option

  dir.stdout.on('data', (data) => {
    console.log(`spawn stdout: ${data}`);
  });

  dir.stderr.on('data', (data) => {
    console.log(`spawn stderr: ${data}`);
  });

  dir.on('error', (code) => {
    console.log(`spawn error: ${code}`);
  });

  dir.on('close', (code) => {
    console.log(`spawn child process closed with code ${code}`);
  });

  dir.on('exit', (code) => {
    console.log(`spawn child process exited with code ${code}`);
  });
})();

My guess here is that because dir is not an actual program (there's no dir.exe in Windows), you have to tell the spawn() command whether it's supposed to run this in a command shell or without a command shell. Whereas on other platforms, things such as ls are actual programs that can be run either way.

like image 62
jfriend00 Avatar answered Aug 04 '26 12:08

jfriend00



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!