node.jsv0.10.4の時点で機能するMarcusPopeの回答の更新バージョン:
ご注意ください:
- 一般に、ノードのストリームインターフェイスはまだ流動的であり(しゃれは半分意図されています)、の時点で分類され
2 - Unstable
ますnode.js v0.10.4
。
- プラットフォームが異なれば、動作も少し異なります。私が調べたところ
OS X 10.8.3
、Windows 7
主な違いは次のとおりです。インタラクティブなstdin入力を同期的に読み取る(端末に1行ずつ入力する)ことは、Windows7でのみ機能します。
更新されたコードは次のとおりです。入力が利用できなくなるまで、256バイトのチャンクでstdinから同期的に読み取ります。
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));
}