从 node.js v0.10.4 开始工作的 Marcus Pope 答案的更新版本:
请注意:
- 一般来说,节点的流接口仍在不断变化(双关语是有意的),并且仍被归类
2 - Unstable
为node.js v0.10.4
.
- 不同平台的行为略有不同;我看过
OS X 10.8.3
and Windows 7
:主要区别是:同步读取交互式标准输入(通过逐行输入终端)仅适用于 Windows 7。
这是更新后的代码,以 256 字节的块从标准输入同步读取,直到没有更多输入可用:
var fs = require('fs');
var BUFSIZE=256;
var buf = new Buffer(BUFSIZE);
var bytesRead;
while (true) { // Loop as long as stdin input is available.
bytesRead = 0;
try {
bytesRead = fs.readSync(process.stdin.fd, buf, 0, BUFSIZE);
} catch (e) {
if (e.code === 'EAGAIN') { // 'resource temporarily unavailable'
// Happens on OS X 10.8.3 (not Windows 7!), if there's no
// stdin input - typically when invoking a script without any
// input (for interactive stdin input).
// If you were to just continue, you'd create a tight loop.
throw 'ERROR: interactive stdin input not supported.';
} else if (e.code === 'EOF') {
// Happens on Windows 7, but not OS X 10.8.3:
// simply signals the end of *piped* stdin input.
break;
}
throw e; // unexpected exception
}
if (bytesRead === 0) {
// No more stdin input available.
// OS X 10.8.3: regardless of input method, this is how the end
// of input is signaled.
// Windows 7: this is how the end of input is signaled for
// *interactive* stdin input.
break;
}
// Process the chunk read.
console.log('Bytes read: %s; content:\n%s', bytesRead, buf.toString(null, 0, bytesRead));
}