我正在编写一个函数来确保节点实例正常关闭。
为此,我确保我unref()
所有套接字。这就是我在做的事情:
function tidyUp(){
console.log("Closing the server...");
server.close();
console.log("Ordering a hotplate shutdown...");
process.emit( 'hotplateShutdown');
// This will give time to server.close() to actually work..
setTimeout( function() {
console.log("Calling unref() for all Sockets and for the Server:");
wtf.dump();
var handles = Array.prototype.slice.call( process._getActiveHandles() );
handles.forEach( ( h, i ) => {
var name = h.constructor.name;
if( h.unref && typeof h.unref == 'function' & ( name == 'Socket' || name == 'Server' ) ){
console.log("Unreffing:", i );
h.unref();
}
});
console.log("After unreffing:");
wtf.dump();
setTimeout( function(){
console.log("This process should soon close");
console.log("Here is the event queue keeping it alive:");
wtf.dump( true );
}, 1000);
}, 1000 );
};
我担心因为服务器也发送电子邮件,我想绝对确保发送的任何内容确实已发送。 基本上是:
"给一个Socket
对象,你怎么知道它是一个INBOUND套接字(一个接收连接,因为节点的HTTP服务器会打开)或一个OUTBOUND套接字(一个由nodemailer
打开以发送电子邮件)。"
我想要unref()
所有入站套接字,并保持出站密码,直到所有电子邮件都已发送。
提示?
答案 0 :(得分:0)
我最终跟踪了打开的入站套接字:
var server = http.createServer(app);
// Keep track of all inbound sockets. They will be
// unref()ed at cleanup time
var inboundSockets = {};
var socketId = 0;
server.on('connection',function( socket ){
socket.__id = socketId ++;
inboundSockets[ socket.__id ] = socket;
socket.on('close',function(){
delete inboundSockets[ socket.__id ];
});
});
process.on('uncaughtException', function (err) {
console.error( "Error caught: ");
console.error(err);
tidyUp();
})
process.on('SIGTERM', function(){
console.log("TERMINATING THIS INSTANCE!");
tidyUp();
});
function tidyUp(){
console.log("Closing the server...");
server.close();
// The next line is important AS IS as it will tell naps that the
// server is no longer functional
console.log("THE SERVER HAS STOPPED");
console.log("Ordering a hotplate shutdown...");
process.emit( 'hotplateShutdown');
// This will give time to server.close() to actually work..
setTimeout( function() {
console.log("Calling unref() for inbound sockets:");
Object.keys( inboundSockets ).forEach( ( __id ) => {
var s = inboundSockets[ __id ];
console.log("Unreffing inbound socket:", s.__id );
s.unref();
});
db.unref();
console.log("After unreffing:");
wtf.dump();
setTimeout( function(){
console.log("This process should soon close");
console.log("Here is the event queue keeping it alive:");
wtf.dump( true );
}, 5000);
}, 1000 );
};
请注意,我在创建时为套接字分配了一个ID(似乎并不是获取唯一ID的明确通用方法),然后在服务器关闭时取消它们...