我需要知道是否可以使用JavaScript将通过stdin输入的每个单词迭代到程序中。如果是的话,我可以得到如何做到这一点的线索吗?
带节点:
var stdin = process.openStdin();
var buf = '';
stdin.on('data', function(d) {
buf += d.toString(); // when data is received on stdin, stash it in a string buffer
// call toString because d is actually a Buffer (raw bytes)
pump(); // then process the buffer
});
function pump() {
var pos;
while ((pos = buf.indexOf(' ')) >= 0) { // keep going while there's a space somewhere in the buffer
if (pos == 0) { // if there's more than one space in a row, the buffer will now start with a space
buf = buf.slice(1); // discard it
continue; // so that the next iteration will start with data
}
word(buf.slice(0,pos)); // hand off the word
buf = buf.slice(pos+1); // and slice the processed data off the buffer
}
}
function word(w) { // here's where we do something with a word
console.log(w);
}
处理stdin比简单的字符串split
复杂得多,因为Node将stdin表示为Stream
(它将传入数据块作为Buffer
发出),而不是字符串。(它对网络流和文件I/O也做同样的事情。)
这是一件好事,因为stdin可以任意大。考虑一下,如果将一个千兆字节的文件管道传输到脚本中会发生什么。如果它先将stdin加载到一个字符串中,首先会花费很长时间,然后在RAM(特别是进程地址空间)用完时崩溃。
通过将stdin作为流处理,您能够以良好的性能处理任意大的输入,因为您的脚本一次只处理小块数据。不利的一面是复杂性明显增加。
上面的代码适用于任何大小的输入,如果一个单词在两个块之间被切成两半,则不会中断。
假设您使用的环境具有console.log
,并且标准输入是字符串,那么您就可以做到这一点。
输入:
var stdin = "I hate to write more than enough.";
stdin.split(/s/g).forEach(function(word){
console.log(word)
});
输出:
I
hate
to
write
more
than
enough.