我用PG-承諾爲維塔利-T建議。而這段代碼工作真快
const fs = require('fs');
const pgp = require('pg-promise')();
const config = require('./config.js');
// Db connection
const db = pgp(config.pg);
// Transform a lot of inserts into one
function Inserts(template, data) {
if (!(this instanceof Inserts)) {
return new Inserts(template, data);
}
this._rawType = true;
this.toPostgres =() => {
return data.map(d => '(' + pgp.as.format(template, d) + ')').join();
};
}
// insert Template
function Insert() {
return {
firstname: null,
lastname: null,
birthdate: null,
phone: null,
email: null,
city: null,
district: null,
location: null,
street: null
};
};
const lineReader = require('readline').createInterface({
input: require('fs').createReadStream('resources/database.csv')
});
let n = 0;
const InsertArray = [];
lineReader.on('line', function(line) {
var insert = new Insert();
n ++;
var InsertValues=line.split(',');
if (InsertValues[0]!=='"Firstname"'){ //skip first line
let i = 0;
for (let prop in insert){
insert[prop] = (InsertValues[i]=='')?insert[prop]:InsertValues[i];
i++;
}
InsertArray.push(insert);
if (n == 10000){
lineReader.pause();
// convert insert array into one insert
const values = new Inserts('${firstname}, ${lastname},${birthdate},${phone},${email},${city},${district},${location},${street}', InsertArray);
db.none('INSERT INTO users (firstname, lastname,birthdate,phone,email,city,district,location,street) VALUES $1', values)
.then(data => {
n = 0;
InsertArray=[];
lineReader.resume();
})
.catch(error => {
console.log(error);
});
}
}
});
lineReader.on('close',function() {
console.log('end '+n);
//last insert
if (n > 0) {
const values = new Inserts('${firstname}, ${lastname},${birthdate},${phone},${email},${city},${district},${location},${street}', InsertArray);
db.none('INSERT INTO users (firstname, lastname,birthdate,phone,email,city,district,location,street) VALUES $1', values)
.then(data => {
console.log('Last');
})
.catch(error => {
console.log(error);
});
}
});
你試過暫停一旦你得到一個線,並恢復一旦查詢的回調被稱爲?我認爲排隊的查詢太多了,這可能會耗盡您的進程內存。 – mscdex
I aded lineReader.pause();在查詢和lineReader.resume()之前;在查詢後,但看起來像沒有工作。相同的錯誤 – m3n1at
請考慮進行批量插入。每行插入太昂貴。 –