管道用于处理小的输入(例如“ foo bar”),也可以处理巨大的文件。
流API确保您可以开始处理数据,而无需等待巨大的文件完全通过管道传输(这对于速度和内存来说更好)。它的方法是为您提供数据块。
没有用于管道的同步API。如果您确实想在做某件事之前将整个管道输入都掌握在手中,则可以使用
注意:仅使用 节点> =0.10.0,因为该示例使用stream2
API
var data = '';function withPipe(data) { console.log('content was piped'); console.log(data.trim());}function withoutPipe() { console.log('no content was piped');}var self = process.stdin;self.on('readable', function() { var chunk = this.read(); if (chunk === null) { withoutPipe(); } else { data += chunk; }});self.on('end', function() { withPipe(data);});用…测试
echo "foo bar" | node test.js
和
node test.js



