How to go from spawn to spawnSync?


I'm doing a bash console using node.js. I have to use spawnSync instead of spawn. How do I make an event occur when a standard output occurs, capture it and send it to the client through a socket?

The code with spawn would be something like this:

var spawn = require('child_process').spawn;
var shell = spawn('/bin/bash');

shell.stdout.on('data', function(data) {
   socket.emit('stdout', data);

socket.on('stdin', function(command) {
    shell.stdin.write(command+"\n") || socket.emit('disable');

I need to know how to do something equivalent with spawnSync. If you need more code or clarify something, ask without fear.

Edit: for what Gustavo has explained, it is not viable to do it with spawnSync. Is there any way to know if a command has finished (correctly or incorrectly)? The fact is that there are commands like cd that do not emit output and I need a "something" (preferably an event) that tells me that it has ended.

asked by Francisco Martin 23.04.2017 в 14:11

1 answer


The child_process.spawnSync function is synchronous, as the name implies. Like fs.readFileSync for example, the EventLoop will be blocked until it has finished running on the stack. In the case of spawnSync , the EventLoop will be blocked until the process has been closed .

The mode of use is simple:

const command = spawnSync('ifconfig', ['eth0']);
// el resto de código se ejecutará cuando se termine el proceso
const outtext = command.output[1];
console.log(outtext); // imprime información de la interface de red
answered by 23.04.2017 в 16:18