读取CSV文件的最后一行并提取一个值 [英] Read the last line of a CSV file and extract one value

查看:311
本文介绍了读取CSV文件的最后一行并提取一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Node.js的新功能,并尝试从CSV文件的最后一行提取值.这是CSV:

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 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:\\\部分.

The part I am trying to grab is file:\\\C:\AlertLog\1_03-06-2013_1120-24.mp3 - preferably getting rid of the file:\\\ part.

对不起,我没有任何代码可以显示,只有对Node.js的经验有几个小时,而且似乎找不到任何有关如何完成此类操作的文档.任何帮助,将不胜感激.谢谢!

Sorry that I do not have any code to show, just have a few hours of experience with Node.js and cannot seem to find any docs on how to accomplish something like this. Any help would be appreciated. Thanks!

推荐答案

常规文件

像常规文件一样读取文件,将文件内容分成几行,最后一行,用逗号分开,最后一部分.

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

文件系统模块文档

您还可以使用 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);
  });

这篇关于读取CSV文件的最后一行并提取一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆