gpt4 book ai didi

node.js - 从外部信号正常关闭 Node.js 程序的最佳做法是什么?

转载 作者:搜寻专家 更新时间:2023-10-31 23:02:46 25 4
gpt4 key购买 nike

从外部信号正常退出 Node.js 程序的最佳做法是什么?

我目前在我的代码中使用它:

process.on( 'SIGINT', function() {
console.log( "\ngracefully shutting down from SIGINT (Crtl-C)" )
// some other closing procedures go here
process.exit( )
})

最佳答案

希望此模板有所帮助。我从 Simon Holmes 的书 Getting MEAN 中得到了大部分内容。归功于他。

var mongoose = require( 'mongoose' );
var gracefulShutdown;
var dbURI = 'mongodb://localhost/xxx';
if (process.env.NODE_ENV === 'production') {
dbURI = process.env.MONGOLAB_URI;
}

mongoose.connect(dbURI);

// CONNECTION EVENTS
mongoose.connection.on('connected', function () {
console.log('Mongoose connected to ' + dbURI);
});
mongoose.connection.on('error',function (err) {
console.log('Mongoose connection error: ' + err);
});
mongoose.connection.on('disconnected', function () {
console.log('Mongoose disconnected');
});

// CAPTURE APP TERMINATION / RESTART EVENTS
// To be called when process is restarted or terminated
gracefulShutdown = function (msg, callback) {
mongoose.connection.close(function () {
console.log('Mongoose disconnected through ' + msg);
callback();
});
};
// For nodemon restarts
process.once('SIGUSR2', function () {
gracefulShutdown('nodemon restart', function () {
process.kill(process.pid, 'SIGUSR2');
});
});
// For app termination
process.on('SIGINT', function() {
gracefulShutdown('app termination', function () {
process.exit(0);
});
});
// For Heroku app termination
process.on('SIGTERM', function() {
gracefulShutdown('Heroku app termination', function () {
process.exit(0);
});
});
// TODO : For Modulus app termination

// BRING IN YOUR SCHEMAS & MODELS.
require('./yyy');

关于node.js - 从外部信号正常关闭 Node.js 程序的最佳做法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9299331/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com