how to import a csv file to mysql using node.js?

前端 未结 1 585
春和景丽
春和景丽 2021-02-08 23:23

Right now I am trying with the library fast-csv doing this:

var stream = fs.createReadStream(\"./google.csv\");
  csv
   .fromStream(stream, {he         


        
1条回答
  •  太阳男子
    2021-02-09 00:16

    You can use node module 'csv-parse'.

    1. read the csv file using node 'fs' module
    2. pass the data to csv parser and you will get arry of array, where inner array represents each row.

    Take a look at the following code.

    var csvParser = require('csv-parse');
    
    fs.readFile(filePath, {
      encoding: 'utf-8'
    }, function(err, csvData) {
      if (err) {
        console.log(err);
      }
    
      csvParser(csvData, {
        delimiter: ','
      }, function(err, data) {
        if (err) {
          console.log(err);
        } else {
          console.log(data);
        }
      });
    });
    

    Here filePath is path of the csv file and the delimiter will be as per your file. It is the character that separates fields in csv file(can be ',', '.', etc).

    0 讨论(0)
提交回复
热议问题