Read the last line of a CSV file and extract one value

后端 未结 2 667
面向向阳花
面向向阳花 2021-02-10 00:30

New to Node.js and trying to pull a value from the very last line of a CSV file. Here is the CSV:

Unit ID,Date,Time,Audio File
Log File Created,3/6/2013,11:18:25         


        
2条回答
  •  抹茶落季
    2021-02-10 01:21

    Regular file

    Read the file like a regular file, split the file contents into lines, take the last line, split by a comma and take the last part.

    var fs = require('fs'); // file system module
    
    fs.readFile('/path/to/file.csv', 'utf-8', function(err, data) {
        if (err) throw err;
    
        var lines = data.trim().split('\n');
        var lastLine = lines.slice(-1)[0];
    
        var fields = lastLine.split(',');
        var audioFile = fields.slice(-1)[0].replace('file:\\\\', '');
    
        console.log(audioFile);
    });
    

    File System module documentation

    CSV parser

    You can also use the node-csv-parser module.

    var fs = require('fs');
    var csv = require('csv');
    
    csv()
     .from.stream(fs.createReadStream('/path/to/file.csv'))
     .to.array(function(data, count) {
        var lastLine = data.slice(-1)[0];
        var audioFile = lastLine.slice(-1)[0].replace('file:\\\\', '');
        console.log(audioFile);
      });
    

提交回复
热议问题