Search code examples
node.jschild-processspawn

Node.js - child process with spawn: can't stream data from child


I want to spawn a child process on windows to open a terminal (cmd.exe). I got everything working, except that i'm not able to stream data from the child process to the parent. I want to access the output from the terminal in the parent process. Here is my code:

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

    var child = spawn('cmd', [ '/c', 'start'], {
        cwd: '{path-to-folder}'
        });


    child.stdout.on('data', function (data) {
        console.log(data);
    });

    child.stderr.on('data', function (data) {
        console.log(data);
    });

    child.on('close', function () {

        console.log('close');
    })

I'm really stuck so any help or tipp would be awesome!! Thanks in advance!


Solution

  • That's because you're starting new shell in new terminal session. You can intercept output only from command that is run same terminal session.

    For example, if you change start to dir you'll have output:

    var child = spawn('cmd', [ '/c', 'dir'], {
        cwd: '.'
        });
    child.stdout.on('data', function (data) {
        console.log(data.toString());
    });
    

    Volume in drive C has no label. Volume Serial Number is 9401-94AE

    Directory of C:\Temp
    
    
    12/02/2015  01:29 PM    <DIR>          .
    12/02/2015  01:29 PM    <DIR>          ..
    12/02/2015  01:30 PM               403 test.js
                   4 File(s)     10,423,442 bytes
                   4 Dir(s)  12,869,840,896 bytes free
    
    close