如何正确关闭节点快递服务器?

我需要关闭后从 /auth/github/callback回调服务器 通常 HTTP://nodejs.org/docs/update/API/HTTP.html”rel = “ noReferrer”> HTTP API 关闭 服务器目前支持 server.close([callback]) API 函数,但是对于 node-Express 服务器,我得到的是 TypeError: Object function app(req, res){ app.handle(req, res); } has no method 'close' 我不知道如何找到信息来解决这个问题。
如何关闭快递服务器?

NodeJS 配置说明:

$ node --version
v0.8.17
$ npm --version
1.2.0
$ npm view express version
3.0.6

实际应用代码:

var app = express();


// configure Express
app.configure(function() {
// … configuration
});


app.get(
'/auth/github/callback',
passport.authenticate('github', { failureRedirect: '/login' }),
function(req, res) {
res.redirect('/');


setTimeout(function () {
app.close();
// TypeError: Object function app(req, res){ app.handle(req, res); } has no method 'close'
}, 3000)
}
);


app.listen('http://localhost:5000/');

此外,我已经找到了 “ nodejs 表示接近...”,但我不确定我是否可以使用它的代码,我有: var app = express();

108970 次浏览

app.listen() returns http.Server. You should invoke close() on that instance and not on app instance.

Ex.

app.get(
'/auth/github/callback',
passport.authenticate('github', { failureRedirect: '/login' }),
function(req, res) {
res.redirect('/');


setTimeout(function () {
server.close();
// ^^^^^^^^^^^
}, 3000)
}
);


var server = app.listen('http://localhost:5000/');
// ^^^^^^^^^^

You can inspect sources: /node_modules/express/lib/application.js

In express v3 they removed this function.

You can still achieve the same by assigning the result of app.listen() function and apply close on it:

var server = app.listen(3000);
server.close((err) => {
console.log('server closed')
process.exit(err ? 1 : 0)
})

https://github.com/visionmedia/express/issues/1366

If any error occurs in your express app then you must have to close the server and you can do that like below-

var app = express();
var server = app.listen(process.env.PORT || 5000)

If any error occurs then our application will get a signal named SIGTERM. You can read more SIGTERM here - https://www.gnu.org/software/libc/manual/html_node/Termination-Signals.html

process.on('SIGTERM', () => {
console.info('SIGTERM signal received.');
console.log('Closing http server.');
server.close((err) => {
console.log('Http server closed.');
process.exit(err ? 1 : 0);
});
});

I have answered a variation of "how to terminate a HTTP server" many times on different support channels. Unfortunately, I couldn't recommend any of the existing libraries because they are lacking in one or another way. I have since put together a package that (I believe) is handling all the cases expected of graceful express.js HTTP(S) server termination.

https://github.com/gajus/http-terminator

The main benefit of http-terminator is that:

  • it does not monkey-patch Node.js API
  • it immediately destroys all sockets without an attached HTTP request
  • it allows graceful timeout to sockets with ongoing HTTP requests
  • it properly handles HTTPS connections
  • it informs connections using keep-alive that server is shutting down by setting a connection: close header
  • it does not terminate the Node.js process

calling server.close does the job

server.close((err) => {
console.log('server closed')
process.exit(err ? 1 : 0)
})

also it is good to listen for system(user) signals and shutdown gracefully on them too, for that you should listen on both SIGTERM and SIGINT

const port = process.env.PORT || 5000;
const server = app.listen(port);
console.log(`listening on port:${port}`);
for (let signal of ["SIGTERM", "SIGINT"])
process.on(signal, () => {
console.info(`${signal} signal received.`);
console.log("Closing http server.");
server.close((err) => {
console.log("Http server closed.");
process.exit(err ? 1 : 0);
});
});


Old question but now Node v18.2.0 introduced server.closeAllConnections(). It should be noted that server.close never runs its callback when the browser sends the request Connection: keep-alive, because server.close only stops the server from accepting new connections, it does not close old connections.

Before Node v18.2.0 I tackled this problem by waiting 5 seconds for the server to shutdown, after which it would force exit.

This code encompasses both situations

process.on('SIGINT', gracefulShutdown)
process.on('SIGTERM', gracefulShutdown)


function gracefulShutdown (signal) {
if (signal) console.log(`\nReceived signal ${signal}`)
console.log('Gracefully closing http server')


// closeAllConnections() is only available from Node v18.02
if (server.closeAllConnections) server.closeAllConnections()
else setTimeout(() => process.exit(0), 5000)


try {
server.close(function (err) {
if (err) {
console.error('There was an error', err)
process.exit(1)
} else {
console.log('http server closed successfully. Exiting!')
process.exit(0)
}
})
} catch (err) {
console.error('There was an error', err)
setTimeout(() => process.exit(1), 500)
}
}