Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodeJS child_process.spawn does not work when one of the args has a space in it

I am trying to use the child_process.spawn function. The syntax is

child_process.spawn(command, args=[], [options])

Whenever I include a space in any of the elements of the args array, the command simply emits the argument. Here is some code I used to test it

var spawn = require("child_process").spawn

console.log("This works");
var watcher = spawn("ls", ["-l"]);
watcher.stdout.on('data', function(data) {
    process.stdout.write(data.toString());
});

console.log("This does not work");
watcher = spawn("ls", ["-l", "/path with space in it"]);
watcher.stdout.on('data', function(data) {
    process.stdout.write(data.toString());
});

Is this a bug in node? Do I need to escape the space?

Edit: The above code is just an example. Here is the real code. Maybe is has to do with the pipes?

watcher = spawn("supervisor", ["--extensions\ 'coffee|js|css|coffeekup'", "src/app.coffee"]);
like image 467
giodamelio Avatar asked Jun 08 '12 00:06

giodamelio


People also ask

What is child_process spawn?

spawn returns an object with stdout and stderr streams. You can tap on the stdout stream to read data that the child process sends back to Node. stdout being a stream has the "data", "end", and other events that streams have.

What is a child_process module in node JS?

Usually, Node. js allows single-threaded, non-blocking performance but running a single thread in a CPU cannot handle increasing workload hence the child_process module can be used to spawn child processes. The child processes communicate with each other using a built-in messaging system.

How do you spawn in node JS?

The spawn function launches a command in a new process and we can use it to pass that command any arguments. For example, here's code to spawn a new process that will execute the pwd command. const { spawn } = require('child_process'); const child = spawn('pwd');


1 Answers

Don't put spaces in args, just use another argument in the array

var watcher = spawn("supervisor", [
  "--extensions",
  "'coffee|js|css|coffeekup'",
  "src/app.coffee"
]);

A handy little shortcut I found if you want to get quick diagnostic output from your child processes is passing the {stdio: "inherit"} in options

var watcher = spawn("supervisor", [
  "--extensions",
  "'coffee|js|css|coffeekup'",
  "src/app.coffee"
], {stdio: "inherit"});

This way you can see whether everything is working properly right away.

Lastly, depending on where supervisor is installed, you might want to consider using the full path.

var watcher = spawn("/path/to/supervisor", ...);
like image 97
maček Avatar answered Oct 11 '22 23:10

maček