Skip to content

Instantly share code, notes, and snippets.

@jackmaney
Created November 29, 2012 07:01
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 jackmaney/4167292 to your computer and use it in GitHub Desktop.
Save jackmaney/4167292 to your computer and use it in GitHub Desktop.
Node fiddling: event wrapper around STDIN reading
var events = require("events");
var util = require("util");
Writer = function(prefix)
{
if(typeof prefix === "undefined")
{
this.prefix = "";
}
else
{
this.prefix = prefix + ": ";
}
this.write = function(chunk)
{
process.stdout.write(prefix + chunk);
}
this.end = function()
{
console.log("KTHXBAI!");
process.exit(0);
}
}
Reader = function(end)
{
if(typeof end === "undefined")
{
this.end = "\n";
}
else if (end !== "\n")
{
this.end = end + "\n";
}
else
{
this.end = end;
}
this.process = function(chunk)
{
chunk = chunk.toString();
if(chunk === this.end)
{
this.emit("end");
}
else
{
this.emit("write",chunk);
}
}
}
util.inherits(Reader,events.EventEmitter);
process.stdin.resume();
process.stdin.setEncoding('utf8');
var reader = new Reader("q");
var writer = new Writer("I got: ");
reader.on("write",writer.write);
reader.on("end",writer.end);
console.log("Input, please:");
process.stdin.on('data',function(chunk){reader.process(chunk);});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment