简体   繁体   English

上传和读取CSV-Parse文件

[英]Uploading And Reading CSV-Parse File

I am trying to read a csv file with multiple same colums using Node CSV-Parser 我正在尝试使用Node CSV-Parser读取具有多个相同列的csv文件

 'from' ' 'to' 'from' ' 'to' 'from' ' 'to'
 'Germ' ' 'NL' 'Turk' ' 'US' 'Nile' ' 'BR'
 'Germ' ' 'NL' 'Turk' ' 'US' 'Nile' ' 'BR'
 'Germ' ' 'NL' 'Turk' ' 'US' 'Nile' ' 'BR'
 'Germ' ' 'NL' 'Turk' ' 'US' 'Nile' ' 'BR'

And below is my code: 以下是我的代码:

req.file('ratefile').upload(function (err, uploadedFile) {
        if (err) return ResponseService.json(500, err, 'Uploaded Failed');

        console.log(uploadedFile.length) //

        if (uploadedFile.length) {
            rs = fs.createReadStream(uploadedFile[0].fd);
            parser = parse({columns: true, trim: true}, function (err, data){
                var record = {};
                console.log(data);
                _.forEach(data, function(datum, index){
                    var routeName = datum['from'] +"-"+ datum['to'];
                    console.log(routeName);
                    record.name = datum['from'] +"-"+ datum['to'];
                    record.to = datum['to'];
                    record.from = datum['from'];
                });

                return ResponseService.json(200, res, 'file successfully uploaded');
            });
            rs.pipe(parser);
        } else {
            return ResponseService.json(500, res, 'Please upload a file')
        }
    });

And when I run that, it only the last column on the csv file. 当我运行它时,它只是csv文件的最后一列。

  'from' ' 'to'
  'Nile' ' 'BR'
  'Nile' ' 'BR'
  'Nile' ' 'BR'

Any help would be appreciated. 任何帮助,将不胜感激。 Thanks 谢谢

It will parse into something like 它会解析成类似的东西

{
  "from": "Germ",
  "to"  : "NL",
  "from": "Turk",
  "to"  : "US",
  ...
}

And of course it's not valid JSON, look at the duplicate keys. 当然它不是有效的JSON,看看重复的键。 So last key value pair will actually overriding previous pair. 因此,最后一个键值对实际上会覆盖前一对。

In your line 在你的行

parser = parse({columns: true, trim: true}, function (err, data){

Use function, or null as columns value, like 使用函数,或null作为columns值,如

parse({columns: null, trim: true}

And print out your parsed result, and then modify by your own needs. 并打印出解析后的结果,然后根据自己的需要进行修改。 It can also use function , but I don't pretty sure function can solve your problems, since it will still parsing your single csv line into single object . 它也可以使用function ,但我不太确定function可以解决你的问题,因为它仍然会将你的单个csv行解析为单个object

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM