lundi 6 avril 2015

async queries to database in nodeJS

I'm trying to parse file with data and insert it in the database, parsing goes well and when I make one query it runs great to, but when I trying to get this queries work in cycle it give me



values: [output[i][0], output[i][1], output[i][2], output[i][3], o
^
TypeError: Cannot read property '0' of undefined


First I was trying simple for loop but after some research about nodeJS being async I find that i need to do this in callback, but it didn't works, I think that parsing is not done by moment of starting queries routine, but I'm not sure.



var express = require('express');
var pg = require('pg');
var csv = require('fast-csv');
var app = express();

var conString = "postgres://alexzander:,tjdekma@localhost/db2015";
var output = [];

var client = new pg.Client(conString);

parser = csv.fromPath("public/dataInputOld/tblOwner.txt", {delimiter: ';'});
parser.on("data", function (data) {
output.push(data);
});

parser.on("end", query(1));

function query(i) {
if (i < 30) {
client.query({
text: 'INSERT INTO tblowner ' +
'(intownerid, txtownersurname, txtownername, txtownersecondname, txtaddress)' +
' VALUES ($1, $2, $3, $4, $5)',
values: [output[i][0], output[i][1], output[i][2], output[i][3], output[i][4]]
}, function (err) {
if (err) {
console.log('error: ' + err)
}
else {
console.log(i);
query(i + 1);
}
});
}
}

app.get('/', function (req, res) {
res.send(JSON.stringify(output[1][0]));
});

var server = app.listen(3001, function () {

var host = server.address().address;
var port = server.address().port;

console.log('App listening at http://%s:%s', host, port);
});


Update: now I think that i didn't connect well to database


Update2: I changed



parser.on("end", query(1));


to



parser.on("end", function(){
query(1);
});


and now error is gone, but nothing inserts in database


Aucun commentaire:

Enregistrer un commentaire