Node.JS数据输入流

时间:2011-07-25 17:12:01

标签: node.js module stream extend

是否有输入流扩展,因此我可以调用像我习惯的方法

例如

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.
})

后端会监听dataenderror个事件并自动缓冲它们,并在我拨打readData时将它们用于。{/ p >

1 个答案:

答案 0 :(得分:2)

此功能并不难。您所要做的就是掌握ReadableStream原型并实现.read方法

未经测试的代码:

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);
    });
};