如何在Node.js中同步解析CSV格式的字符串?
Node.js中同步解析CSV字符串(无需异步读取文件)
问题场景
已有包含特殊字符(逗号、引号等)的CSV格式字符串,需要同步解析为数组;同时希望能将数组反向编码为符合CSV规范的字符串,而非通过异步方式读取CSV文件。
原异步读取CSV文件的示例代码:
const fs = require("fs"); const { parse } = require("csv-parse"); const readCSV = () => { fs.createReadStream("./testfile.csv").pipe( parse({ delimiter: ",", from_line: 1 }) .on("data", function (row) { console.log(row); }) .on("end", function () { console.log("finished"); }) .on("error", function (error) { console.log(error.message); }) ); };
待解析的CSV字符串(已对单引号转义):
const encodedString = 'Guatemala,United States,"Congo, ""Dem."" Rep. \'of\' `the` (Kinshasa)",other country name';
期望解析结果:
[ 'Guatemala', 'United States', 'Congo, "Dem." Rep. \'of\' `the` (Kinshasa)', 'other country name', ]
解决方案
使用csv-parse(同步解析)和csv-stringify(同步编码)包,二者均支持直接处理字符串/数组,无需异步IO操作。
1. 安装依赖
npm install csv-parse csv-stringify
2. 同步解析CSV字符串
const { parse } = require("csv-parse"); function parseCSVString(csvStr) { const options = { delimiter: ",", from_line: 1 }; // parse直接处理字符串,返回二维数组,取第一个元素即为目标行的数组 const [result] = parse(csvStr, options); return result; } // 测试 const encodedString = 'Guatemala,United States,"Congo, ""Dem."" Rep. \'of\' `the` (Kinshasa)",other country name'; const parsedArray = parseCSVString(encodedString); console.log(parsedArray); // 输出:[ 'Guatemala', 'United States', 'Congo, "Dem." Rep. \'of\' `the` (Kinshasa)', 'other country name' ]
3. 同步将数组编码为CSV字符串
const { stringify } = require("csv-stringify"); function arrayToCSV(arr) { const options = { delimiter: ",", quoted: true }; // 把目标数组包裹为二维数组代表一行数据,trim去除末尾自动添加的换行 return stringify([arr], options).trim(); } // 测试 const targetArray = [ 'Guatemala', 'United States', 'Congo, "Dem." Rep. \'of\' `the` (Kinshasa)', 'other country name', ]; const csvString = arrayToCSV(targetArray); console.log(csvString); // 输出:Guatemala,United States,"Congo, ""Dem."" Rep. 'of' `the` (Kinshasa)",other country name
说明
parse函数默认支持同步处理字符串/Buffer,无需通过流操作即可直接返回解析结果stringify的quoted: true配置会自动对包含特殊字符的字段添加引号,并转义内部的双引号,符合CSV规范
内容的提问来源于stack exchange,提问作者josealvarez97
相关产品推荐
相关产品推荐

