NodeJs: Detect when program started with child_process.spawn is ready?

1.8k views Asked by At

I use the spawn function from node's child process module to start mpv player and then communicate through a unix socket with it.

My problem is, that when spawning mpv it is not yet ready and right away. I'd like something like a callback or a promise to see when the mpv process is ready.

spawn('mpv', arguments, function() {
    // mpv ready
});

I though about using a promise by "pinging" the socket and resolve it, when it is successful. But I'm not very familiar with promises yet.

Does anybody happen to have some experience with that?

1

There are 1 answers

5
Denis Lisitskiy On

I dont know, why you want to do this in promise way, you can do some code when you recive some data in data handler..

I think, you can try with promise in this way

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

function spawnAsyncFunction() {
    var proc = spawn('ls', ['-l']);
    return new Promise(function (resolve, reject) {
        proc.stdout.on('data', function (data) {
            resolve(data);
        });
        proc.on('close', function (code) {
            reject(code);
        });

    })

}
spawnAsyncFunction()
    .then(function(data){
        // Some usful code here
        console.log(data.toString());
    })
    .catch(function (error) {
        console.log(error);
    });