我的方法来自这个方法,它基本上按照@Ege Özcan 所说的那样做。
唯一的补充是我设置了关闭服务器的路由,因为节点没有从我的终端('SIGTERM'
和'SIGINT'
)获得信号。
好吧,节点在执行时从我的终端获取信号,node whatever.js
但是当将该任务委托给脚本(如'start'
package.json --> 中的脚本npm start
)时,它未能被关闭Ctrl+C
,所以这种方法对我有用。
请注意,我在Cygwin下,对我来说,在这之前杀死服务器意味着关闭终端并重新打开它。
另请注意,我使用express进行路由。
var http=require('http');
var express= require('express');
var app= express();
app.get('/', function (req, res) {
res.send('I am alive but if you want to kill me just go to <a href="/exit">/exit</a>');
});
app.get('/exit', killserver);
var server =http.createServer(app).listen(3000, function(){
console.log('Express server listening on port 3000');
/*console.log(process);*/
});
// Maintain a hash of all connected sockets
var sockets = {}, nextSocketId = 0;
server.on('connection', function (socket) {
// Add a newly connected socket
var socketId = nextSocketId++;
sockets[socketId] = socket;
console.log('socket', socketId, 'opened');
// Remove the socket when it closes
socket.on('close', function () {
console.log('socket', socketId, 'closed');
delete sockets[socketId];
});
// Extend socket lifetime for demo purposes
socket.setTimeout(4000);
});
// close the server and destroy all the open sockets
function killserver() {
console.log("U killed me but I'll take my revenge soon!!");
// Close the server
server.close(function () { console.log('Server closed!'); });
// Destroy all open sockets
for (var socketId in sockets) {
console.log('socket', socketId, 'destroyed');
sockets[socketId].destroy();
}
};