Search code examples
node.jsmodulestreamextend

Node.JS Data Input Stream


Is there a input stream extension so I can call methods like I am used to

For example

stdin.readData(function (err, buffer) { // err if an error event was created, buffer if this is just data, null to both if the end of the stream was reached.
    // Added bonuses would be other methods I am used to in Java
    // - readLine
    // - readFully
    // - readStringUtf8
    // - readInt, readDouble, readBoolean, etc.
})

The backend would be listening for data, end, and error events and automatically buffer them and just have them available for when I call readData.


Solution

  • This functionality isn't hard to do. All you have to do is get hold of the ReadableStream prototype and implement the.readmethod

    Untested Code:

    var ReadableStream = Object.getPrototypeOf(process.stdin);
    
    ReadableStream.read = function(cb) {
        this.on('data', function(buf) {
            cb(null, buf);
        });
    
        this.on('error', function(err) {
            cb(err, null);    
        });
    
        this.on('end', function() {
            cb(null, null);
        });
    
        this.on('close', function() {
            cb(new Error("Stream closed"), null);
        });
    };