Skip to content

Instantly share code, notes, and snippets.

@vire

vire/nodeEvents2.js

Created Nov 17, 2013
Embed
What would you like to do?
var util = require('util'),
eventEmitter = require('events').EventEmitter,
fs = require('fs');
function inputChecker(name, file) {
this.name = name;
this.writeStream = fs.createWriteStream('./'+ file + ".txt",
{
'flags': 'a',
'encoding': 'utf8',
'mode': '0666'
});
}
// melds inputChecker with eventEmitter together
util.inherits(inputChecker, eventEmitter);
// function that check the input
inputChecker.prototype.check = function check(input) {
var command = input.toString().trim().substr(0,3);
if (command == 'wr:' ) {
// if the command starts with 'wr:', then emit an event
// 'write' and the callback function is transformation
// of the input string without the first 3 chars (=== command)
this.emit('write', input.substr(3, input.length));
} else if (command == 'en:') {
// if the command starts with 'en:' the program emits 'end' and the
// .on listeners executes process.exit();
this.emit('end');
} else {
// if none of above matches to the command, just emit the 'echo' event
//
this.emit('echo', input);
}
};
// new object testing and event handling
var ic = new inputChecker('ACustomString','outputfile');
ic.on('write', function(data) {
this.writeStream.write(data, 'utf8');
});
ic.on('echo', function(data) {
console.log(this.name + " wrote " + data);
});
ic.on('end', function() {
process.exit();
});
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', function(input) {
ic.check(input);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.