Recently I have been busy with nodejs and I thought to create something like this Java input library, so I started with some rough code like below:
'use strict';
const readline = require('readline');
const fs = require('fs');
class StdIn {
constructor(opt_name) {
this.name = opt_name;
this.rs = this.name ? fs.createReadStream(this.name) : process.stdin
}
readInt(callback) {
this.rs.on('data', (chunk) => {
let line = chunk.toString();
let numbers = line.trim().split(/\s/);
numbers.forEach(num => {
callback.call(this, num);
});
});
this.rs.on('end', () => {
process.exit(0);
});
}
readLine(callback) {
this.rs.on('data', (chunk) => {
let line = chunk.toString();
callback.call(this, line);
});
this.rs.on('end', () => {
process.exit(0);
});
}
}
const stdIn = new StdIn(process.argv[2]);
//stdIn.readInt(num => {
// console.log(num);
//});
stdIn.readLine(line => {
console.log(line);
});
Its working fine till now and buts its still incomplete and the code is too messy, the problem clearly visible here that I am trying to push event oriented code into my object oriented world, I am confused basically for two things:
- It is practical to do so?
- If yes then what would be the best way?