node.js:如何检测一个空的标准inputstream?

我有一个node.js脚本/服务器,读取stdin启动时的一些input。 但是,有时候没有数据要传入。这很麻烦,因为在这种情况下, data和事件都不会被调用。 如何检测node.js代码中的情况?

我想避免在input结尾附加特殊的“结束”字符,以免给客户带来不便。 相关的代码如下:

  var newHTML = ''; var gfm = spawn(__dirname + '/node_modules/docter/bin/github-flavored-markdown.rb'); process.stdin.on('data', function(chunk){ gfm.stdin.write(chunk); }); process.stdin.on('end', function(){ gfm.stdin.end(); }); gfm.stdout.on('data', function(data) { newHTML += data; }); gfm.on('exit',function(ecode){ socket.emit('newContent', newHTML); }); process.stdin.resume(); 

我相信可能发生的事情是,你根本没有给予足够的热情。

ØysteinSteimler的例子显示了将/ dev / null添加到您的应用程序中:

节点pipe.js </ dev / null

但是,当你不把stdin传递给应用程序的时候,从来没有解决过。 只是运行node pipe.js不会退出,因为它仍然在等待stdin

你可以用其他的unix程序自己testing一下,例如cat

尝试运行这个:

 cat < /dev/null 

现在尝试运行:

 cat 

它不会退出,因为它正在等待stdin。 您可以inputterminal并按回车键发送到程序。 它仍然不会退出(并等待更多的input),直到它收到你可以用CTRL + D做的EOF

process.stdinend事件检测到一个空的或没有STDINstream。

这个简单的脚本stdin.js表明:

 process.stdin.on( 'data', function(data) { console.log( data ) } ); process.stdin.on( 'end', function() { console.log( 'EOF' ) } ); 

不同的场景:

 $ echo test | node stdin.js <Buffer 74 65 73 74 0a> EOF $ echo -n | node stdin.js EOF $ node stdin.js < /dev/null EOF $ 

这个脚本pipe.js演示了如何使用pipe道生成subprocess:

 var spawn = require('child_process').spawn; var cat = spawn( '/bin/cat' ); cat.stdout.on( 'data', function(data) { console.log( data ) } ); cat.stdout.on( 'end', function() { console.log( 'EOF' ) } ); process.stdin.pipe(cat.stdin); 

正如所料:

 $ echo test | node pipe.js <Buffer 74 65 73 74 0a> EOF $ echo -n | node pipe.js EOF $ node pipe.js < /dev/null EOF $ 

你可以做的事情就是让你的应用程序接受一个像-s这样的参数,这使得它从标准input读取。

LiveScript的CLI工具就是这样做的:

-s, --stdin read stdin