我有一个csv文件,想在node.js/express中使用。如何将文件转换为数组/JSON/string类型的变量。我尝试过:
fs.readFile('Resource.csv', function(err, data) {
console.log(data)}
我也尝试了一些在SO上找到的其他方法,但都不适用于我。如果数据有多行,则可能会影响结果。
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
(和本地化)的字符集。 - Aikon Mogwainpm i --save csvtojson
。然后你可以像这样使用该模块: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"}
]
const csvtojson=require('csvtojson')
模块,则应该使用 csvtojson(...).fromFile(...).then。 - L. Faros