如何使用node.js将csv文件导入到mysql? [英] how to import a csv file to mysql using node.js?

查看:399
本文介绍了如何使用node.js将csv文件导入到mysql?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,我正在尝试使用库 fast-csv :

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");
   });

但是它抛出此错误:预期的列标题不匹配:2列:57"

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?

推荐答案

您可以使用节点模块'csv-parse'.

You can use node module 'csv-parse'.

  1. 使用节点"fs"模块读取csv文件
  2. 将数据传递给csv解析器,您将获得arry的array,其中内部array代表每一行.

看看下面的代码.

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);
    }
  });
});

此处filePath是csv文件的路径,分隔符将根据您的文件.它是分隔csv文件中字段的字符(可以是',','.'等).

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

这篇关于如何使用node.js将csv文件导入到mysql?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆