process.stdin.on中的一點沒有理解的地方
发布于 10 年前 作者 telnetning 8493 次浏览 最后一次编辑是 8 年前

node版本爲0.10.26,在這個版本中已經建議不用stdin.pause了。
下面是官方文檔一段代碼

process.stdin.setEncoding('utf8');
//process.stdin.pause();
process.stdin.on('readable', function(chunk) {
  console.log("function內部");
  var chunk = process.stdin.read();
  if (chunk !== null) {
    process.stdout.write('data: ' + chunk);
  }
});

process.stdin.on('end', function() {
    process.stdout.write('end');
});

如果第二行註釋加上,沒什麼問題。
但是如果去掉註釋,結果是這樣的:

telnetning[@debian](/user/debian):/var/www/node$ node t_readable.js 
Hello
funciton內部

也就是function已經調用了,輸入爲Hello,但是chunk卻沒有得到值,想問問這是怎麼回事?新手提問,還望包涵。


已經佔到解釋了,node的github中issue有人提到這個問題,isaacs給出了解釋:

You shouldn't be calling read() and also calling resume(). The resume() function puts it into  
flowing-mode, and all the data just pours out in data events. So, the data's already been consumed,  
 and, that's why read() returns null, because there is nothing in teh buffer.

Just call read(). There's no need to resume() anything if you're using that interface

大意是使用read的時候不應該使用resume,使用resume會導致輸入進入流模式,用來觸發了data事件,已經被消耗, read於是不能讀取到任何內容。 鏈接在這裏:https://github.com/joyent/node/issues/5813

1 回复

已經解決,謝謝關注。

回到顶部