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

后端 未结 2 676
面向向阳花
面向向阳花 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:12

    I did it in by reading the file backwards until last line was read:

    var fs = require('fs');
    var path = require('path');
    var fileName = path.join(__dirname, 'test.txt');
    var readLastLine = function(name, callback) {
        fs.stat(name, function(err, stat) {
            fs.open(name, 'r', function(err, fd) {
                if(err) throw err;
                var i = 0;
                var line = '';
                var readPrevious = function(buf) {
                    fs.read(fd, buf, 0, buf.length, stat.size-buf.length-i, function(err, bytesRead, buffer) {
                        if(err) throw err;
                        line = String.fromCharCode(buffer[0]) + line;
                        if (buffer[0] === 0x0a) { //0x0a == '\n'
                            callback(line);
                        } else {
                            i++;
                            readPrevious(new Buffer(1));
                        }
                    });
                }
                readPrevious(new Buffer(1));
            });
        });
    }
    readLastLine(fileName, function(line) {
        console.log(line);
    });
    

提交回复
热议问题