Node.js port listening and reading from stdin at the same time
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 cli开发者_C百科ents, 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?
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);
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)
精彩评论