Node.js port listening and reading from stdin at the same time

隐身守侯 提交于 2019-12-22 18:15:35

问题


I have a socket server in Node.js and I'd like to be able to read from stdin at the same time the server is listening. It works only partially. I'm using this code:

process.stdin.on('data', function(chunk) {
    for(var i = 0; i < streams.length; i++) {
        // code that sends the data of stdin to all clients
    }
});

// ...

// (Listening code which responds to messages from clients)

When I don't type anything, the server responds to messages of the clients, but when I start typing something, it isn't until I press Enter that it continues with this task. In the time between starting to type something and pressing Enter, the listening code seems to be suspended.

How can I make the server still respond to clients while I'm typing in stdin?


回答1:


I just wrote a quick test and had no problems processing input from stdin and http server requests at the same time, so you'll need to provide detailed example code before I can help you. Here's the test code which runs under node 0.4.7:

var util=require('util'),
    http=require('http'),
    stdin=process.stdin;

// handle input from stdin
stdin.resume(); // see http://nodejs.org/docs/v0.4.7/api/process.html#process.stdin
stdin.on('data',function(chunk){ // called on each line of input
  var line=chunk.toString().replace(/\n/,'\\n');
  console.log('stdin:received line:'+line);
}).on('end',function(){ // called when stdin closes (via ^D)
  console.log('stdin:closed');
});

// handle http requests
http.createServer(function(req,res){
  console.log('server:received request');
  res.writeHead(200,{'Content-Type':'text/plain'});
  res.end('success\n');
  console.log('server:sent result');
}).listen(20101);

// send send http requests
var millis=500; // every half second
setInterval(function(){
  console.log('client:sending request');
  var client=http.get({host:'localhost',port:20101,path:'/'},function(res){
    var content='';
    console.log('client:received result - status('+res.statusCode+')');
    res.on('data',function(chunk){
      var str=chunk.toString().replace(/\n/,'\\n');
      console.log('client:received chunk:'+str);
      content+=str;
    });
    res.on('end',function(){
      console.log('client:received result:'+content);
      content='';
    });
  });
},millis);



回答2:


Are you running your script as a background process using &? Otherwise the console is the controlling terminal of the process, and is probably sending a SIGSTOP message when you're typing to avoid race conditions or something.

Try running the process as node myprocess.js &

If it still happens, try nohup node myprocess.js &.

http://en.wikipedia.org/wiki/Signal_(computing)



来源:https://stackoverflow.com/questions/6063111/node-js-port-listening-and-reading-from-stdin-at-the-same-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!