如何在node.js中将.csv转换为数组/JSON/字符串

6

我有一个csv文件,想在node.js/express中使用。如何将文件转换为数组/JSON/string类型的变量。我尝试过:

fs.readFile('Resource.csv', function(err, data) {
    console.log(data)}

我也尝试了一些在SO上找到的其他方法,但都不适用于我。如果数据有多行,则可能会影响结果。


https://www.npmjs.com/package/csvtojson - L. Faros
我尝试过了,但是出现了 TypeError: csv(...).fromFile(...).then 不是一个函数。 - ddy250
你确定已经安装并且需要该npm模块了吗? - L. Faros
是的。@L.Faros 我确定。 - ddy250
另外,如果您需要使用 const csvtojson=require('csvtojson') 模块,则应该使用 csvtojson(...).fromFile(...).then。 - L. Faros
2个回答

18
var fs = require('fs');

var data = fs.readFileSync('Resource.csv')
    .toString() // convert Buffer to string
    .split('\n') // split string to lines
    .map(e => e.trim()) // remove white spaces for each line
    .map(e => e.split(',').map(e => e.trim())); // split each line to array

console.log(data);
console.log(JSON.stringify(data, '', 2)); // as json

我在控制台中得到了奇怪的字符。可能是编码错误。 - ddy250
1
使用 fs.readFileSync('Resource.csv', <codepage>)。通常控制台无法正确处理 utf-8(和本地化)的字符集。 - Aikon Mogwai
2
如果CSV的任何字段包含逗号字符,则此解决方案无法正常工作。 - Kerry Gougeon
很棒的解决方案 - 非常整洁 - omeanwell
1
不行。这个解决方案只适用于大多数情况下适合的最简单的csv。根据维基百科 csv值可以被引用并包含\n。你应该在生产中使用一个特殊的库。 - Aikon Mogwai

6
为了进一步解释我在csvtojson文档中的评论,安装方法为:npm i --save csvtojson。然后你可以像这样使用该模块:
CSV文件:
a,b,c
1,2,3
4,5,6

JS 代码:

const csvFilePath='<path to csv file>' // Resource.csv in your case
const csv=require('csvtojson') // Make sure you have this line in order to call functions from this modules
csv()
.fromFile(csvFilePath)
.then((jsonObj)=>{
    console.log(jsonObj);
})

输出:

[
  {a:"1", b:"2", c:"3"},
  {a:"4", b:"5". c:"6"}
]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接