How to read csv file in node js

前端 未结 3 1606
星月不相逢
星月不相逢 2021-01-17 10:18

I am trying to read a csv file using node js. Her is my code

fs.readFile(config.csvUploadPath, function read(err, data) {
    if (err) {
        throw err;
         


        
3条回答
  •  南方客
    南方客 (楼主)
    2021-01-17 11:15

    Use a library, CSV has lots of gotchas. I have come to enjoy the package csv. It is located here: https://www.npmjs.com/package/csv . Here is a very quick example using the async api.

    const fs = require('fs')
    var parse = require('csv-parse')
    fs.readFile(inputPath, function (err, fileData) {
      parse(fileData, {columns: false, trim: true}, function(err, rows) {
        // Your CSV data is in an array of arrys passed to this callback as rows.
      })
    })
    

    Since your file does not have multiple values per row and contains no delimiters besides newline, it is only trivially CSV. Maybe String.prototype.split() is for you?

    const fs = require('fs')
    fs.readFile(inputPath, 'utf8', function (err, data) {
      var dataArray = data.split(/\r?\n/);  //Be careful if you are in a \r\n world...
      // Your array contains ['ID', 'D11', ... ]
    })
    

提交回复
热议问题