javascript - Node script doesn't ever end -
i have node script below copy contents of files , insert them mongo.
the script never seems end , though data gets inserted successfully, have ctrl+c kill it.
is there i'm supposed use in node.js end script?
var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/testdb'); var dir = './seeds'; var db = mongoose.connection; // show connection error if there 1 db.on('error', console.error.bind(console, 'database connection error:')); // if connected mongo db.once('open', function callback() { var fs = require('fs'); // used files in directory // read files in folder fs.readdir(dir, function(err, list) { // log error if went wrong if(err) { console.log('error: '+err); } // every file in list list.foreach(function(file) { // set filename without extension variable collection_name var collection_name = file.split(".")[0]; var parsedjson = require(dir + '/' + file); for(var = 0; < parsedjson.length; i++) { // counts number of records in collection db.collection('cohort').count(function(err, count) { if(err) { console.log(err); } }); db.collection(collection_name).insert(parsedjson[i], function(err, records) { if(err) { console.log(err); } console.log(records[0]); console.log("record added "+records[0]); }); } }); }); });
when done, call mongoose.disconnect()
. @aarondufour correctly points out, node not exit while event handler callbacks registered because doesn't know no more events expected, connection emitting 'close' or 'error' event, example.
Comments
Post a Comment