Skip to content

Instantly share code, notes, and snippets.

@nibral
Created February 4, 2016 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nibral/0d0936092409fd44ba31 to your computer and use it in GitHub Desktop.
Save nibral/0d0936092409fd44ba31 to your computer and use it in GitHub Desktop.
// 標準入力から1行ずつ読み込み
var readLineFromStdin = function(callback) {
process.stdin.resume();
process.stdin.setEncoding('utf8');
// 入力(の一部)が到着
var fragment = '';
process.stdin.on('data', function(chunk) {
if (chunk === '') {
return;
}
// 行の一部が到着した分(fragment)は次の処理に回す
var lines = chunk.split('\n');
lines[0] = fragment + lines[0];
fragment = lines.pop();
// 各行をコールバックに渡す
lines.forEach(function(line) {
callback(line);
});
});
// 入力終了
process.stdin.on('end', function() {
// 残ったデータを出力
if (fragment !== '') {
callback(fragment);
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment