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

纵然是瞬间 提交于 2019-12-12 07:53:05

问题


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

var stream = fs.createReadStream("./google.csv");
  csv
   .fromStream(stream, {headers : ["Name","E-mail 1 - Value"], ignoreEmpty: true})
   .on("data", function(data){
       console.log(data);
   })
   .on("end", function(){
       console.log("done");
   });

But it throws this error: "column header mismatch expected: 2 columns got: 57"

Do you know how can I avoid that? should I use a different library/approach

Another problem I am facing is that I get the result in hexadecimal... how can I parse it correctly?


回答1:


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).



来源:https://stackoverflow.com/questions/26638569/how-to-import-a-csv-file-to-mysql-using-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!