mongoclient.connection does not return cursor back on command line

半腔热情 提交于 2019-12-14 02:55:00

问题


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)?


回答1:


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();
});


来源:https://stackoverflow.com/questions/18746444/mongoclient-connection-does-not-return-cursor-back-on-command-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!