Node.js flow data from a terminal command to a client

Here were a few questions about node.js execution of command execution and data output, but I still can't get this to work. I want with node.js I want to execute a python script that works for a long time and produces some intermediate outputs. I want to transfer these results to the client as soon as they are created. I tried the following, but I get that I get all the output only after the command completes. How can I transfer data to a socket in real time? Thanks.

function run_cmd(cmd, args) {
  var spawn = require('child_process').spawn,
  child = spawn(cmd, args);
  return child;
}

io.sockets.on('connection', function (socket) {
  var foo = new run_cmd('python', ['test.py']);
  foo.stdout.setEncoding('utf-8');
  foo.stdout.on('data', function(data) {
     console.log('sending data');
     io.sockets.emit('terminal', {output: data});;
  });
);
+4
source share
1 answer

all your node.js code is fine. Your code only sends data once because your code only receives data once.

puts foo.stdout.on '$ stdout.flush' , ruby-. .

.

JS

var spawn = require('child_process').spawn;
var cmd  = spawn('ruby', ['testRuby.rb']);
var counter = 0;
cmd.stdout.on('data', function(data) {
    counter ++;
  console.log('stdout: ' + data);
});

cmd.stderr.on('data', function(data) {
  console.log('stderr: ' + data);
});

cmd.on('exit', function(code) {
  console.log('exit code: ' + code);
  console.log(counter);
});

testRuby.rb

def execute_each_sec(sleep_sec)
  yield
  sleep sleep_sec
end

5.times do
  execute_each_sec(1) do ||
    puts "CurrentTime:#{Time.now}"
    $stdout.flush
  end
end

, $stdout.flush testRuby.rb. , node.js , testRuby.rb .

. ruby ​​ python. python, sys.stdout.flush(), svkk

Edit: python -u, . ​​

+6

Source: https://habr.com/ru/post/1524893/


All Articles