【问题标题】:How can I convert from .csv to array/json/string in node.js如何在 node.js 中从 .csv 转换为 array/json/string
【发布时间】:2021-04-18 06:09:48
【问题描述】:

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

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

还尝试了一些我可以在 SO 中找到的其他东西,但没有一个对我有用。如果重要,数据是多行的。

【问题讨论】:

  • 我试过了,得到:TypeError: csv(...).fromFile(...).then is not a function
  • 您确定安装并需要 npm 模块吗?
  • 是的。 @L.Faros 我敢肯定。
  • 另外,如果您需要带有const csvtojson=require('csvtojson') 的模块,那么您应该使用 csvtojson(...).fromFile(...).then

标签: node.js csv express


【解决方案1】:
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

【讨论】:

  • 我在控制台中得到了奇怪的字符。可能编码错误。
  • 使用fs.readFileSync('Resource.csv', <codepage>)。控制台通常无法正确使用utf-8(和国家本地化)。
  • 如果 csv 的任何字段包含“,”字符,则此解决方案不起作用。
  • 很好的解决方案 - 非常整洁
  • 不。此解决方案仅适用于适用于大多数情况的最简单的 csv。根据Wiki csv 值可以被引用并包含\n。您应该使用特殊的库进行生产。
【解决方案2】:

扩展我的评论(来自 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"}
]

【讨论】:

    猜你喜欢
    • 2017-01-30
    • 1970-01-01
    • 2013-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-15
    • 2022-12-17
    • 2015-12-11
    相关资源
    最近更新 更多