我有一个node.js脚本/服务器,可以在启动时从标准输入中读取一些输入。但是,有时没有数据可以传递。这很麻烦,因为在这种情况下似乎既没有调用data
事件,也没有调用end
事件。如何在node.js代码中检测到这种情况?
我希望避免在输入的末尾附加特殊的" end“字符,以免给客户端带来不便。相关代码如下:
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();
发布于 2013-10-23 06:50:39
来自process.stdin
的end
事件检测到STDIN流为空或没有STDIN流。
这个简单的脚本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
演示了使用管道指向派生的子进程的效果非常好:
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
$
发布于 2015-02-24 23:39:33
你可以做的就是让你的应用程序接受一个像-s
这样的参数,让它从标准输入中读取。
这就是LiveScript的CLI工具所做的事情:
-s, --stdin read stdin
https://stackoverflow.com/questions/9231847
复制相似问题