nodejs event stream setting a variable per stream

僤鯓⒐⒋嵵緔 提交于 2019-12-25 01:43:17

问题


I have a code that creates a readable stream . I would like to set the name of the stream in the getStream method . I tried setting a property as shown below . I am able to access the property in the onceFunction but I am not able to access the property in the map Function . Let me know what I am doing wrong

var onceFunction = function(str1,record) {
    console.log("OnceFunction",this.nodeName);
}
var getStream = function(csvData) {
    var dirNames = csvData.split("/");
    var nodeName = dirNames[dirNames.length-2];
    var fileName = csvData;
    stream = fs.createReadStream(csvData);
    stream.nodeName = dirNames[dirNames.length-2];

    return stream;
};
var myFileList = ["D:\mypath\file"];

for ( var i = 0; i< myFileList.length; i++ ) {
    getStream(myFileList[i])
        .once('data',onceFunction)
        .pipe(es.split())
        .on('end',endFunction)
        .pipe(es.map(function(data,cb) {
            console.log(this.nodeName);

        }));
}

回答1:


Because "es" has it's own "this". And passes it to es.map callback. Where, ofcource, nodeName is empty. Refactor you code to use closures and avoid using "this". For example in pseudocode:

for ( var i = 0; i< myFileList.length; i++ ) {
    processFile(myFileList[i]);
}

var processfile = function(file) {
    var stream = getStream(file);
    var somevar = stream.nodeName;
    stream.once('data',onceFunction)
        .pipe(es.split())
        .on('end',endFunction)
        .pipe(es.map(function(data,cb) {
            console.log(somevar);
            console.log(stream.nodeName);
        }));
}


来源:https://stackoverflow.com/questions/27108692/nodejs-event-stream-setting-a-variable-per-stream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!