简体   繁体   English

如何从javascript中的本地.csv文件读取以填充字符串数组?

[英]How to read from local .csv file in javascript to fill an array of strings?

I have a CSV file with 100 names per line.我有一个每行 100 个名称的 CSV 文件。 I want to create an array containing each name.我想创建一个包含每个名称的数组。 Currently, my CSV file looks like this:目前,我的 CSV 文件如下所示:

Names
Bob
Joe
Tim
Allan 

and I want to fill the array as follows:我想按如下方式填充数组:

const csv = require('csv-parser');
const fs = require('fs');    
const names= [];
fs.createReadStream('./Names.csv')
  .pipe(csv())
  .on('data', (data) => names.push(data.Names))
  .on('error', (error) => loggingService.getDefaultLogger().error(error))
  .on('end', () => loggingService.getDefaultLogger().info("Array of Names:" + names));

Using a logging service I've created I see all names from the CSV.使用我创建的日志服务,我可以看到 CSV 中的所有名称。 When I do console.log(names) I get an empty array.当我执行 console.log(names) 时,我得到一个空数组。 Might anyone know why this is?可能有人知道这是为什么吗? More specifically is there a better way to read from a CSV file so that I can fill an array of strings with the contents of that file, 1 array entry as a string per line?更具体地说,是否有更好的方法来读取 CSV 文件,以便我可以用该文件的内容填充字符串数组,每行 1 个数组条目作为字符串?

May work but not sure.可能工作,但不确定。

Edit : Yup working like a charm.编辑:是的,工作就像一个魅力。

const fs = require('fs');

let Names = [];

fs.readFile('./names.csv', 'utf8', (err, dat) => {
  if(err)
    console.error("Error while opening file");

  Names = String(dat).split('\n');
});

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

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