请求完成后,nodejs表示关闭服务器 [英] nodejs express close server when request is done

查看:106
本文介绍了请求完成后,nodejs表示关闭服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为模块编写测试脚本,完成请求后,我需要能够关闭服务器.以下代码可以正常工作,但我可以看到app.close()已从express 3中删除.现在最好的方法是什么?

I'm writing a test script for my module and I need to be able to close my server when my request is done. The following code works but I can see that app.close() was dropped from express 3. What's the best way to do it now?

var testCase = require('nodeunit').testCase;
var request = require('request');
var express = require('express');

var app = express.createServer();
var srv = app.listen();
....

request({
    method: 'POST',
    json: true,
    body: { id: 'second request'},
    url: 'http://' + target
  }, function(err, res, body) {

    console.info("closing server");
    app.close();
    test.done();
  });
});

谢谢, 李

p.s.关闭服务器后必须调用test.done(),否则测试将失败.

p.s. test.done() must be called after closing the server, otherwise the test will fail.

推荐答案

用于从http.Server继承的Express应用程序,它们不再这样做,而这正是close方法的来源.而是在您的srv实例上调用close().您可能通常会看到此代码写为:

Express applications used to inherit from http.Server, which they no longer do, and that's where the close method came from. Instead, call close() on your srv instance. You may commonly see this code written as:

var app = express.createServer();
var srv = require('http').createServer(app);
srv.listen(port);

根据app.listen()文档:

绑定并侦听给定主机和端口上的连接,此方法与节点的http.Server#listen()相同.

这篇关于请求完成后,nodejs表示关闭服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆