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

I have a socket server in Node.js and I would like to be able to read from stdin while listening to the server. It works only partially. I am 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 do not type anything, the server responds to client messages, but when I start typing something, it only happens after I press Enter to continue this task. Between the start of typing something and pressing Enter, the listen code seems to be locked.

How can I make the server still respond to client requests while I type stdin?

+2
source share
2 answers

I just wrote a quick test and had no problems handling input from stdin and http server requests at the same time, so you will need to provide a detailed sample code before I can help you. Here is the test code that works 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); 
+6
source

Are you using a script as a background process with & ? Otherwise, the console is the control terminal of the process and probably sends a SIGSTOP message when you print to avoid race conditions or something else.

Try to start the process as node myprocess.js &

If this still happens try nohup node myprocess.js & .

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

+1
source

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


All Articles