2019年1月16日 星期三

node.js http 讀取 stream

function pstreamPipe(path, callback, code){
    return (streamPipe(path, callback, code)[0]);
}


function streamPipe(path, callback, code) {
    let def = _.deferred();


    let stream = require("fs").createReadStream(path);
    if (code) {
        stream.setEncoding(code);
    }

    stream.on('data', function (data) {
        callback(data);
    });

    stream.on('error', function (err) {
        def.reject(err);
    });

    stream.on('end', function () {
        def.resolve();
    });

    return [def.promise(), stream];
}