问题
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'.
- read the csv file using node 'fs' module
- 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