I have a baconjs
stream I use to save articles with mongoose
. Here's the code:
function main() {
db.once('open', function(callback) {
console.log('db connection successs');
console.log('stremaing page ' + page);
var stream = readSite(page);
stream.onValue(function(article) {
try {
article = toArticleModel(article);
} catch (e) {
console.error(e);
}
article.save(function(err, article) {
if (err) {
console.error('Save Error: ' + err);
} else {
console.log('saved ' + article.publishedDate + " " + article.author.name + " " + article.title);
}
});
stream.onError(function(err) {
console.error('Stream Error: ' + err);
});
stream.onEnd(function() {
console.log('stream ended closing in 15 seconds..');
setTimeout(function() {
db.close();
}, 15 * 1000);
});
});
});
Once the stream ends onEnd
, I want to close the db connection and exit the nodejs program. I figured once the stream ends I should wait for some time so the latest values gets saved to the db. So I use setTimeout
for 15 seconds and use db.close
.
The problem is, the log stream ended closing in 15 seconds..
is logged 50-60 times in the stdout, Why? And is this a good approach to exit such a program?