Node.js用空白字段导入csv

我正在尝试使用csv-parse包导入&parsing一个CSV文件,但是在首先require csv文件时遇到困难。

当我做input = require('../../path-to-my-csv-file')

由于连续的逗号,我得到一个错误,因为有些字段是空的:

 e","17110","CTSZ16","Slitzer™ 16pc Cutlery Set in Wood Block",,"Spice up ^ SyntaxError: Unexpected token , 

如何将CSV文件导入节点环境?

包示例在这里

要解决您的第一个问题,请使用空白条目阅读CSV:

使用'fast-csv'节点包。 它将用emtpy条目parsingcsv。

要回答你的第二个问题,如何将CSV导入到节点中:

你不真的“导入”CSV文件到节点。 您应该打开文件或使用fs.createReadStream在适当的位置读取csv文件。

下面是一个脚本,它使用fs.createReadStreamparsing一个名为“test.csv”的CSV文件,该文件是运行它的脚本的一个目录。

第一部分设置我们的程序,使对象的基本声明将用于存储我们的parsing列表。

 var csv = require('fast-csv') // require fast-csv module var fs = require('fs') // require the fs, filesystem module var uniqueindex = 0 // just an index for our array var dataJSON = {} // our JSON object, (make it an array if you wish) 

下一节将声明一个数据stream,该数据stream将从我们的CSV文件中读取数据并对其进行处理。 在这种情况下,我们拦截数据并将其存储在JSON对象中,然后在stream完成后保存该JSON对象。 它基本上是一个拦截数据的filter,可以做它想要的。

 var csvStream = csv() // - uses the fast-csv module to create a csv parser .on('data',function(data){ // - when we get data perform function(data) dataJSON[uniqueindex] = data; // - store our data in a JSON object dataJSON uniqueindex++ // - the index of the data item in our array }) .on('end', function(){ // - when the data stream ends perform function() console.log(dataJSON) // - log our whole object on console fs.writeFile('../test.json', // - use fs module to write a file JSON.stringify(dataJSON,null,4), // - turn our JSON object into string that can be written function(err){ // function(err) only gets performed once were done saving the file and err will be nil if there is no error if(err)throw err //if there's an error while saving file throw it console.log('data saved as JSON yay!') }) }) 

本节从我们的csv文件创build所谓的“readStream”。 该文件的path是相对的。 stream只是读取文件的一种方式。 这是非常强大的,因为从一个stream的数据可以传输到另一个stream。 因此,我们将创build一个从我们的CSV文件中读取数据的stream,然后在第2节中将其stream入我们预先定义的读取stream/filter。

 var stream = fs.createReadStream('../test.csv') stream.pipe(csvStream) 

这将从我们的csvparsing脚本所在的地方创build一个名为“test.json”的文件。 test.json将在JSON对象中包含parsing的CSV列表。 代码在这里出现的顺序是它应该如何出现在您制作的脚本中。