如何在Node.js中从.csv转换为array/json/string [英] How can I convert from .csv to array/json/string in node.js

查看:83
本文介绍了如何在Node.js中从.csv转换为array/json/string的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a csv file I want to use in node.js/express. How can I convert the file to a variable of type array/json/string. I've tried:

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

还尝试了一些我可以在SO中找到的其他东西,但对我没有任何帮助.如果重要的话,数据可以是多行.

And also tried a number of other things I could find in SO but none work for me. The data is of multiple rows if it matters.

推荐答案

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

这篇关于如何在Node.js中从.csv转换为array/json/string的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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