Skip to content

Instantly share code, notes, and snippets.

@sujoyu
Last active September 23, 2016 08:23
Show Gist options
  • Save sujoyu/393fafacea414711aecbcd682d102774 to your computer and use it in GitHub Desktop.
Save sujoyu/393fafacea414711aecbcd682d102774 to your computer and use it in GitHub Desktop.
javascript sequential stdin reader.
var reader = new Reader(10);
var input = {};
reader.read(function(line) {
var vars = line.split(' ')
input.m = parseInt(vars[0]);
input.n = parseInt(vars[1]);
}).then(reader.read(function(line) {
input.o = line;
})).then(function() {
input.xs = [];
var promise = Promise.resolve();
for (var i = 0; i < input.m; i++) {
promise = promise.then(reader.read(function(line) {
input.xs.push(line);
}));
}
return promise;
}).then(function() {
reader.close();
console.log('input: ');
console.log(input); // main process
}).catch(function(e) {
console.error(e);
});
function Reader(maxLines) {
var lines = [];
for (var i = 0; i < maxLines; i++) {
var line = {
resolve: null,
setLine: function(line) { this.resolve(line); }
}
line.promise = new Promise(function(resolve) {
line.resolve = resolve;
})
lines.push(line);
}
var reader = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
var initr = 0
reader.on('line', function (line) {
lines[initr].setLine(line);
initr++;
});
var itr = 0
this.read = function(func) {
line = lines[itr];
itr++;
return line.promise.then(func)
}
this.close = function() {
reader.close();
}
}
@sujoyu
Copy link
Author

sujoyu commented Sep 23, 2016

$ node reader.js
3 2
foo
a
b
c
input:
{ m: 3, n: 2, o: 'foo', xs: [ 'a', 'b', 'c' ] }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment