读取CSV文件的最后一行并提取一个值

2ul0zpep  于 2022-12-06  发布在  其他
关注(0)|答案(2)|浏览(183)

刚接触Node.js,尝试从CSV文件的最后一行提取值。CSV文件如下:

Unit ID,Date,Time,Audio File
Log File Created,3/6/2013,11:18:25 AM,file:\\\C:\Users\Ben\Documents\1_03-06-2013_1114-50.mp3
1,3/6/2013,11:20:24 AM,file:\\\C:\AlertLog\1_03-06-2013_1120-24.mp3
1,3/6/2013,11:20:39 AM,file:\\\C:\AlertLog\1_03-06-2013_1120-24.mp3

我试图抓取的部分是file:\\\C:\AlertLog\1_03-06-2013_1120-24.mp3-最好是去掉file:\\\部分。
抱歉,我没有任何代码显示,只是有几个小时的经验与Node.js,似乎找不到任何文档如何完成这样的事情。任何帮助将不胜感激。谢谢!

wecizke3

wecizke31#

常规文件

像读普通文件一样读文件,把文件内容拆成行,取最后一行,用逗号分开,取最后一部分。

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

文件系统模块文档

CSV解析器

您也可以使用node-csv-parser模块。

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

3pvhb19x2#

我是这样做的:倒着阅读文件,直到读完最后一行:

更新2022(仅使用一次现代JavaScript和读取缓冲区)

import { open } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const fileName = path.join(__dirname, 'test.txt');

async function readLastLine(name) {
  var line = '';
  var chunkSize = 200 // how many characters to read from the end of file
  const fd = await open(name);
  const st = await fd.stat();
  const buf = Buffer.alloc(chunkSize);
  const len = buf.length;
  const { bytesRead, buffer } = await fd.read(buf, 0, len, st.size - len)
  for (let i = len - 1; i > -1; i--) {
    const isEol = buffer[i] === 0x0a // 0x0a == '\n'
    const isCtrl = buffer[i] < 0x20 // 0-31 are ASCII control characters
    if (isEol && line.length > 0) {
      break;
    } else if (!isCtrl && !isEol) {
      line = String.fromCharCode(buffer[i]) + line;
    }
  }
  fd.close();
  return line;
}

try {
  const line = await readLastLine(fileName)
  console.log(line);
} catch (err) {
  console.error(err);
}

2014年旧答案

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

相关问题