1

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();
  });
});

Thanks, Li

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

user429400
  • 3,145
  • 12
  • 49
  • 68

1 Answers1

2

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);

According to the documentation for app.listen():

Bind and listen for connections on the given host and port, this method is identical to node's http.Server#listen().

Michelle Tilley
  • 157,729
  • 40
  • 374
  • 311
  • I tried to run this with express 2.5 and it gives me the following error: throw new Error('addListener only takes instances of Function'); I guess "app" is not an instance of a Function in express 2.5... Any idea how to manipulate the code so it will work? (I want the code to run on express 2.5 and higher versions) – user429400 Nov 11 '12 at 15:36
  • They have two different interfaces, so you'd need to write two versions of the code. I suppose you could check `typeof app` to see if it's a function or not. – Michelle Tilley Nov 11 '12 at 17:20
  • so if it's a function I should use the new code, and if not I should use the old code with the app.close()? – user429400 Nov 11 '12 at 17:25
  • That seems reasonable to me. Since even in Express 3, `app.listen()` returns a Server, it would take care of both instances. – Michelle Tilley Nov 11 '12 at 17:39
  • Note that `server.close()` will only close the response is sent and if the client is not keeping a persistent HTTP connection. Refer to https://dev.to/gajus/how-to-terminate-a-http-server-in-node-js-ofk – Gajus Jan 20 '20 at 09:17