Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spawn on Node JS (Windows Server 2012)

When I run this through Node:

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

ls = spawn('ls', ['C:\\Users']);

ls.on('error', function (err) {
  console.log('ls error', err);
});

ls.stdout.on('data', function (data) {
    console.log('stdout: ' + data);
});

ls.stderr.on('data', function (data) {
    console.log('stderr: ' + data);
});

ls.on('close', function (code) {
    console.log('child process exited with code ' + code);
});

I get the following error:

ls error { [Error: spawn ENOENT] code: 'ENOENT', errno: 'ENOENT', syscall: 'spawn' }
child process exited with code -1

On Windows Server 2012. Any ideas?

like image 445
fire Avatar asked Aug 20 '13 11:08

fire


2 Answers

As of node 8 per document, you need to set shell option to true (which is false by default).

spawn('dir', [], { shell: true })

Documentation here

like image 175
Gorky Avatar answered Oct 19 '22 12:10

Gorky


As badsyntax pointed out, ls doesn't exist on windows as long as you didn't create an alias. You will use 'dir'. The difference is dir is not a program, but a command in windows shell (which is cmd.exe), So you would need to run 'cmd' with arguments to run dir and output the stream.

var spawn = require('child_process').spawn
spawn('cmd', ['/c', 'dir'], { stdio: 'inherit'})

By using 'inherit', the output will be piped to the current process.

like image 17
Andrew Chaa Avatar answered Oct 19 '22 13:10

Andrew Chaa