mongoclient.connection 不会在命令行上返回光标 [英] mongoclient.connection does not return cursor back on command line

查看:59
本文介绍了mongoclient.connection 不会在命令行上返回光标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的 test1.js

This is my test1.js

console.log("foo");

当我运行 test1.js 时,我得到了命令行

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

$ node test2.js
foo
$

这是我的 test2.js,使用 MongoDbClient

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

但是,当我运行 test2.js 时,我必须按 CTRL-C 才能返回命令行

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

推荐答案

Node.js 不会关闭应用程序,因为订阅了一些事件并且可能发生潜在的逻辑.

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

当您创建 MongoClient 时,它也会创建 EventEmitter,它不会让 node.js 进程退出,因为它可能会接收一些事件.

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. 很好地杀死所有 EventEmitter 和空闲计时器和间隔,然后进程将退出.但很难实现.
  2. 只需调用:process.exit(0) 这将很好地关闭进程.
  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.

同时检查 refunref 的计时器功能(间隔、超时):http://nodejs.org/api/timers.html#timers_unref

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

如果使用 MongoClient,请在完成后关闭数据库连接:

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

这篇关于mongoclient.connection 不会在命令行上返回光标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆