mirror of
https://github.com/danbulant/sql2csv
synced 2026-05-24 12:35:47 +00:00
sql2csv 1.0.0
This commit is contained in:
parent
44702a053b
commit
35b7f8c0f6
1 changed files with 34 additions and 3 deletions
37
sql2csv.js
37
sql2csv.js
|
|
@ -36,6 +36,7 @@ class sql2csv {
|
||||||
}
|
}
|
||||||
if(!this.options.prefix) this.options.prefix = "[SQL2CSV] ";
|
if(!this.options.prefix) this.options.prefix = "[SQL2CSV] ";
|
||||||
if(this.options.colors == undefined) this.options.colors = true;
|
if(this.options.colors == undefined) this.options.colors = true;
|
||||||
|
if(this.options.crlf == undefined) this.options.crlf = false;
|
||||||
|
|
||||||
if(!this.options.skipMysqlCheck){
|
if(!this.options.skipMysqlCheck){
|
||||||
try {
|
try {
|
||||||
|
|
@ -53,14 +54,44 @@ class sql2csv {
|
||||||
}
|
}
|
||||||
|
|
||||||
query(sql){
|
query(sql){
|
||||||
|
var self = this;
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
this.conn.query(sql, function (err, result) {
|
this.conn.query(sql, function (err, result) {
|
||||||
if (err) reject(err);
|
if (err) reject(err);
|
||||||
console.log(result);
|
var csv = "";
|
||||||
resolve(result);
|
var keys = [];
|
||||||
});
|
var keysEmpty = true;
|
||||||
|
result.forEach((row) => {
|
||||||
|
for(var key in row){
|
||||||
|
if(keysEmpty) keys[keys.length] = key;
|
||||||
|
var column = row[key];
|
||||||
|
if(typeof column == "string"){
|
||||||
|
column = column.replace('"', '""');//double quotes, regarding https://stackoverflow.com/questions/4617935
|
||||||
|
if(column.indexOf(",") != -1){
|
||||||
|
column = '"' + column + '"';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
csv += column + ",";
|
||||||
|
}
|
||||||
|
keysEmpty = false;
|
||||||
|
if(self.options.crlf) csv += "\r";
|
||||||
|
csv += "\n";
|
||||||
|
});
|
||||||
|
if(self.options.showNames){
|
||||||
|
var header = "";
|
||||||
|
keys.forEach((key) => {
|
||||||
|
key.replace('"', '""');//double quotes, regarding https://stackoverflow.com/questions/4617935
|
||||||
|
key.replace(",", '","');
|
||||||
|
header += key + ",";
|
||||||
|
});
|
||||||
|
if(self.options.crlf) header += "\r";
|
||||||
|
header += "\n";
|
||||||
|
csv = header + csv;
|
||||||
|
}
|
||||||
|
resolve(csv);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
//update certain option
|
//update certain option
|
||||||
setOption(name, value){
|
setOption(name, value){
|
||||||
this.options[name] = value;
|
this.options[name] = value;
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue