Created
November 17, 2013 20:12
-
-
Save vire/7517697 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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