node.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > node.js > Node.js读取本地CSV文件并且写入为JSON格式文件

Node.js读取本地CSV文件并且写入为JSON格式文件过程

作者:小火车况且况且

本文介绍了使用Node.js v14.18.1读取CSV文件并处理中文乱码的方法,包括使用`fs.readdirSync`读取文件夹、`TextDecoder`处理编码、以及如何解析和处理CSV数据

下面使用到的API都是基于目前版本

1. 格式

1.1 项目文件夹格式

1.2.CSV文件格式

2. 操作

外层循环时,需要注意i=1开始, 因为不需要遍历表头数据

完整代码

const fs = require('fs')
const dirs = fs.readdirSync('./static')

dirs.filter(dir => /\.csv$/.test(dir)).forEach(dir => {
    const file = fs.readFileSync(`./static/${fileName}`)
  	const getGBK = new TextDecoder('gbk').decode(file).split('\r\n')
  	// 获取表头, 用于组装数据
  	const headList = getGBK[0].split(',')
    const headLen = headList.length
    const gbkLen = getGBK.length
    // 遍历文件, 注意是从 i = 1 开始, 因为不需要表头
	for (let i = 1; i < gbkLen; i++) {
	    const gbkItem = getGBK[i]
	    const childList = gbkItem.split(',')
	    if (childList.length === 1) break // 说明该数据是空数据格式
	    const obj = {}
	    // 遍历表头数组
	    for (let j = 0; j < headLen; j++) {
	      const headItem = headList[j]
	      obj[headItem] = childList[j]
	    }
	    json.push(obj)
	  }
	  // 得到不需要文件后缀的名称
	  const getFile = fileName.split('.')[0]
	  // 写入文件数据
	  fs.writeFileSync(`./file/${getFile}.json`, JSON.stringify(json))
	})

最后结果

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文