返回值在函数外部不起作用?

时间:2019-03-23 12:43:18

标签: node.js node-csv-parse

当我们在.on('end')函数返回日志中使用console.log(restaurantdata),但是在函数外部日志无法给出未定义的值返回时。

    var restaurantdata=[];
    fs.createReadStream('restaurantsa9126b3.csv')  
    .pipe(csv())
    .on('data', (data) => restaurantdata.push(data))  
    .on('end', () => {
        return restaurantdata; 

      }) 
      console.log(restaurantdata);
      yield this.render('home',{
        restaurantdata:restaurantdata,
    });

1 个答案:

答案 0 :(得分:1)

您可以尝试...

function convert(data) {
    data = data.split('\n');
    var heading = data[0].split(',');
    var arr = [];
    var line,words,err;
    for(var i=1;i<data.length-1 ;++i){
        var obj = {};
        line=data[i];
        words = line.split(',');
        var k =0;
        for(var j=0;j<words.length;++j){
            if (words[j].indexOf('\"')==-1){
                obj[heading[k]] = words[j];
                k++;
            } else{
                err = [];
                err.push(words[j].substring(1,words[j].length));
                j++;
                while (words[j].indexOf('\"')==-1) {
                    err.push(words[j]); j++;
                }
                err.push(words[j].substring(0,words[j].length-1));
                obj[heading[k]] = err;
                k++;
            }
        }
        arr.push(obj);
    }
   return arr;
}

希望,这可能对您有帮助...