Node.js 关闭连接服务器

Node.js 关闭连接服务器,node.js,connect,Node.js,Connect,我看到了很多关于如何使用创建服务器的示例,但是如何在没有ctrl+c的情况下优雅地关闭它呢 我的用例是启动一个轻量级连接服务器以进行测试/模拟。连接使用节点的内置HTTP库,所以您可以调用server.close() . 您也可以使用process.exit(0)退出应用程序;返回启动应用程序的shell 请记住,http.close()只是停止接受新连接,这取决于应用程序的结构,它可能仍然无法退出。在现有连接自行关闭之前,将对其进行维修 下面是一个混合使用Connect和http的示例: va

我看到了很多关于如何使用创建服务器的示例,但是如何在没有ctrl+c的情况下优雅地关闭它呢


我的用例是启动一个轻量级连接服务器以进行测试/模拟。

连接使用节点的内置HTTP库,所以您可以调用server.close() . 您也可以使用process.exit(0)退出应用程序;返回启动应用程序的shell

请记住,http.close()只是停止接受新连接,这取决于应用程序的结构,它可能仍然无法退出。在现有连接自行关闭之前,将对其进行维修

下面是一个混合使用Connect和http的示例:

var connect = require('connect')
   , http = require('http');

var app = connect()
   .use(connect.favicon())
   .use(connect.logger('dev'))
   .use(connect.static('public'))
   .use(connect.directory('public'))
   .use(connect.cookieParser())
   .use(connect.session({ secret: 'my secret here' }))
   .use(function(req, res){
      res.write('Hello from Connect!\n');
      res.end();
      //stop accepting new connections:
      srv.close();
      //exit the app too:
      process.exit(0);


});

var srv =  http.createServer(app).listen(3000);                                              

我刚刚意识到,不是这样编写服务器:

var app = connect()
.use(function(req, res, next){
    res.end('hello world')
})
.listen(3000); 
var app = connect()
.use(function(req, res, next){
    res.end('hello world')
}); 
var server = http.createServer(app).listen(3000, done);
我可以通过以下方式创建服务器:

var app = connect()
.use(function(req, res, next){
    res.end('hello world')
})
.listen(3000); 
var app = connect()
.use(function(req, res, next){
    res.end('hello world')
}); 
var server = http.createServer(app).listen(3000, done);

因此,允许我使用
server.close()

是否有一种连接方法可以公开该服务器?我正在编辑我的答案,以展示这种创建服务器的方法,但你抢先一步。