Reputation: 141
I have a Node.js app that uses Express.js to listen for connections. The code is something like so:
const express = require("express");
var server = express();
server.get("/test", (req, res) => testResponse(req, res));
server.listen(9001);
console.info("Server is listening to port 9001.");
I'd like to implement a way to restart the server without having to restart the whole app. However, I can't seem to properly shut down the server and free the port. Here's what I tried:
server.close();
console.info("Server closed. Restarting.");
var server = express();
server.get("/test", (req, res) => testResponse(req, res));
server.listen(9001);
console.info("Server is listening to port 9001.");
As soon as I run this, I get
Error: listen EADDRINUSE :::9001
What would be the correct way to do this?
Cheers.
Upvotes: 4
Views: 9184
Reputation: 5088
As of Express 3, the app.close()
method seems to have disappeared, which means Express users have no means of gracefully stopping an application. Express is really a listener to http request events which means you can do this:
const express = require("express");
var server = express();
server.get("/test", (req, res) => testResponse(req, res));
var app = server.listen(9001, function () {
console.log('Listening :)');
app.close(function () {
console.info("Server closed. Restarting.");
var server = express();
server.get("/test", (req, res) => testResponse(req, res));
server.listen(9001);
console.info("Server is listening to port 9001.");
});
});;
console.info("Server is listening to port 9001.");
For more on this you can refer hardening nodejs for production
Upvotes: 0
Reputation: 26878
server.close()
is asynchronous and takes a callback. Try waiting until the server is actually closed before starting a new one:
server.close(()=>{
console.info("Server closed. Restarting.");
var server = express();
server.get("/test", (req, res) => testResponse(req, res));
server.listen(9001);
console.info("Server is listening to port 9001.");
});
Upvotes: 2