I have the following simple node application for data insertion into postgres database:
var pg = require('pg');
var dbUrl = 'tcp://user:psw@localhost:5432/test-db';
pg.connect(dbUrl, function(err, client, done) {
for (var i = 0; i < 1000; i++) {
client.query(
'INSERT into post1 (title, body, created_at) VALUES($1, $2, $3) RETURNING id',
['title', 'long... body...', new Date()],
function(err, result) {
if (err) {
console.log(err);
} else {
console.log('row inserted with id: ' + result.rows[0].id);
}
});
}
});
After I run node app.js in terminal it inserts 1000 rows into database, then application hangs, and it do not terminates. What I am doing wrong? I have looked into pg module examples but didn’t spot that I’m doing any thing differently…
I missed call to the client.end(); Now application exits properly:
pg.connect(dbUrl, function(err, client, done) {
var i = 0, count = 0;
for (i = 0; i < 1000; i++) {
client.query(
'INSERT into post1 (title, body, created_at) VALUES($1, $2, $3) RETURNING id',
['title', 'long... body...', new Date()],
function(err, result) {
if (err) {
console.log(err);
} else {
console.log('row inserted with id: ' + result.rows[0].id);
}
count++;
console.log('count = ' + count);
if (count == 1000) {
console.log('Client will end now!!!');
client.end();
}
});
}
});