Question

This is my test1.js

console.log("foo");

When I run the test1.js, I got the command line back

$ node test2.js
foo
$

This is my test2.js, using MongoDbClient

var MongoClient = require('mongodb').MongoClient;

MongoClient.connect("mongodb://local.host/test?w=1", function(err, db) {
   console.log("foo");
});

However when I run test2.js, I have to press CTRL-C to get the command line back

$ node test3.js
foo
^C
$

What's the difference? and What should I do to get the command line back(close connection, maybe)?

Was it helpful?

Solution

Node.js will not close application while there is some events subscribed and potential logic can happen.

When you create MongoClient it creates EventEmitter as well and it will not let node.js process to exit as it potentially can receive some events.

If you want to get cursor back - then you have few options:

  1. Nicely kill all EventEmitters and idling timers and intervals and process will then exit. But it is hard to achieve.
  2. Just call: process.exit(0) which will nicely close process.

As well check ref and unref for timer functions (interval, timeout): http://nodejs.org/api/timers.html#timers_unref

In case with MongoClient, just close database connection when you are done with it:

var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/testdb', function(err, db) {
  // do your stuff

  // when you are done with database, make sure to respect async queries:
  db.close();
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top