事件的NodeJS设置流每流的可变 [英] nodejs event stream setting a variable per stream

查看:301
本文介绍了事件的NodeJS设置流每流的可变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个code,创建一个可读的流。我想设置在getStream方法的流的名称。我试着设置属性,如下图所示。我能够访问该onceFunction财产,但我不能够访问地图功能属性。让我知道我做错了。

  VAR onceFunction =功能(STR1,记录){
    的console.log(OnceFunction,this.nodeName);
}
VAR getStream =功能(csvData){
    变种dirnames中= csvData.split(/);
    变种节点名称= dirnames中[dirNames.length-2];
    变种文件名= csvData;
    流= fs.createReadStream(csvData);
    stream.nodeName = dirnames中[dirNames.length-2];    返回流;
};
VAR myFileList = [D:\\ mypath中\\文件];对于(VAR I = 0; I< myFileList.length;我++){
    getStream(myFileList [I])
        。一旦(数据,onceFunction)
        .pipe(es.split())
        。对(结束,endfunction可)
        .pipe(es.map(功能(数据,CB){
            的console.log(this.nodeName);        }));
}


解决方案

由于ES拥有自己的本。并通过它来es.map回调。其中,ofcource,节点名称是空的。重构你code使用封闭并避免使用本。
例如,在伪code:结果

 为(VAR I = 0; I< myFileList.length;我++){
    processFile(myFileList [I]);
}变种processfile =函数(文件){
    VAR流= getStream(文件);
    VAR somevar = stream.nodeName;
    stream.once(数据,onceFunction)
        .pipe(es.split())
        。对(结束,endfunction可)
        .pipe(es.map(功能(数据,CB){
            的console.log(somevar);
            的console.log(stream.nodeName);
        }));
}

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

        }));
}

解决方案

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

这篇关于事件的NodeJS设置流每流的可变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆