问题描述
如果我的 Node JS 应用无法连接到 Mongo,我希望它立即退出.我正在使用 mongodb
节点库.
I'd like my Node JS app to exit immediately if it can't connect to Mongo. I'm using the mongodb
node library.
我已将代码缩减为
const {MongoClient} = require('mongodb');
MongoClient.connect('mongodb://localhost:27017');
如果 Mongo 未运行,我会收到带有 ECONNREFUSED
的 UnhandledPromiseRejectionWarning
,这是我完全预料到的,但随后程序挂起并且永不退出.这是 Node 版本 10.0.0.
If Mongo is not running, I get an UnhandledPromiseRejectionWarning
with ECONNREFUSED
, which I fully expect, but then the program hangs and never exits. This is with Node version 10.0.0.
由于连接从未成功,我没有要关闭的连接句柄.我尝试了各种方法来catch
被拒绝的承诺,但我一直没有成功让程序退出.
Since the connection never succeeded I don't have a connection handle to close. I've tried various ways to catch
the rejected promise, but I have been unsuccessful in getting the program to exit.
在这种情况下,我需要做什么来关闭 MongoClient 并使程序退出?
What do I need to do to shut down the MongoClient and make the program exit in this case?
推荐答案
您的应用程序保持活动状态,因为它正在尝试 重新连接.您可以尝试禁用重新连接:
Your application is remaining alive because it is trying to reconnect. You can try disabling the recconect:
MongoClient.connect('mongodb://localhost:27017', {
autoReconnect: false
}, (err, client) => {
if (client) client.close();
});
或者,您可以使用 process.exit(1)终止进程代码>
杀死程序.
Or, you can terminate the process using process.exit(1)
to kill the program.
const {
MongoClient
} = require('mongodb');
// Callback syntax
MongoClient.connect('mongodb://localhost:27017', (err, db) => {
if (err) process.exit(1);
});
// Promise syntax
MongoClient
.connect('mongodb://localhost:27017')
.catch(err => {
process.exit(1);
});
// Async/await syntax
(async function() {
let db;
try {
db = await MongoClient.connect('mongodb://localhost:27017');
} catch (err) {
process.exit(1);
}
}());
这篇关于mongo连接失败时如何让节点退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!