简体   繁体   中英

NodeJS Fork - React each time a newline is sent by subprocess

I am trying to write a function with NodeJS (on Windows7 if that makes a difference) that will listen to subprocess and, after each newline is sent via the subprocess, handle it in Node. Check out this example:

var express = require('express');
var app = express();

app.listen(3000);

app.get('/', function(request, response) {
    var exec = require('child_process').exec,
        child, out = "NA";

    child = exec('java -jar misc.jar',
        function (error, stdout, stderr) {
            if(stdout!==''){
                out = '---------stdout: ---------\n' + stdout;
            }
            if(stderr!==''){
                out = '---------stderr: ---------\n' + stderr;
            }
            if (error !== null) {
                out = '---------exec error: ---------\n[' + error+']';
            }
            response.send(out);
        });
});

As you can imagine, the function (error, stdout, stderr) only gets called after my subprocess is terminated.

Instead, I'd like that function to get called whenever a new line of text comes out of either stdout, stderr. At that point, I'd like to use AJAX/Socket.IO to dynamically update the user-facing html page. (Definitely bonus points if you can help point me in that direction as well!)

Okay I realized I need to use "spawn" and not "exec" to do this:

var express = require('express');
var app = express();

app.listen(3000);

app.get('/', function(request, response) {
    response.send("Hey");
    var spawn = require('child_process').spawn;
    var java = spawn('java', ['-jar', 'misc.jar']);

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

});

However, I notice that express with "response" is not allowing my to push data. So, I need to figure out that last part of my question as I believe to do this I need to use AJAX/Socket.IO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM