简体   繁体   中英

Restarting Web server when config file changes using NodeJS

I have a simple and working web server written in NodeJS as below:

var http = require("http");
var fs = require("fs");

console.log("Web server started");
var config = JSON.parse(fs.readFileSync("./private/config.json"));

var server = http.createServer(function(req,res){

    console.log("received request: " + req.url);
    fs.readFile("./public" + req.url,function(error,data){

        if (error){

            // Not sure if this is a correct way to set the default page? 
            if (req.url === "/"){
                res.writeHead(200,{"content-type":"text/plain"});
                res.end("here goes index.html ?");
            }

            res.writeHead(404,{"content-type":"text/plain"});
            res.end(`Sorry the page was not found.\n URL Request: ${req.url}`);
        } else {
            res.writeHead(200,{"content-type":"text/plain"});
            res.end(data);
        }

    });
});

Now I want my web server to restart and listen to a new port when port number changes in the config file. So I add below code:

fs.watch("./private/config.json",function(){
    config = JSON.parse(fs.readFileSync("./private/config.json"))
    server.close();
    server.listen(config.port,config.host,function(){
        console.log("Now listening: "+config.host+ ":" +config.port);
    });
});

This works fine and when I change the port on config file, I can access my web server on the new port. However, I also can access it on the previous port as well. I thought I am closing my web server on the previous port before I listen to the new port. What am I missing ?

I appreciate your help :)

As Mukesh Sharma mentioned, Server.close() stops accepting new connections and keeps existing connections. That is, server stays open for all alive sockets(until they naturally die due to keep-alive time) but no new sockets will be created.

I found out this question can be a possible duplicate of this question

So I followed the suggested solution mentioned by Golo Roden in the link and it worked. Basically you need to remember open socket connections and destroy them after you close the server. Here is my modified code:

var http = require("http");
var fs = require("fs");

console.log("Web server started");
var config = JSON.parse(fs.readFileSync("./private/config.json"));

var server = http.createServer(function(req,res){

    console.log("received request: " + req.url);
    fs.readFile("./public" + req.url,function(error,data){

        if (error){

            // Not sure if this the correct method ? 
            if (req.url === "/"){
                res.writeHead(200,{"content-type":"text/plain"});
                res.end("welcome to main page");
            }

            res.writeHead(404,{"content-type":"text/plain"});
            res.end(`Sorry the page was not found.\n URL Request: ${req.url}`);
        } else {
            res.writeHead(200,{"content-type":"text/plain"});
            res.end(data);
        }

    });
});

server.listen(config.port,config.host,function(){
    console.log("listening: "+config.host+ ":" +config.port);
});

var sockets = {}, nextSocketId = 0;
server.on('connection', function (socket) {

  // Add a newly connected socket
  var socketId = nextSocketId++;
  sockets[socketId] = socket;
  console.log('socket', socketId, 'opened');

  // Remove the socket when it closes
  socket.on('close', function () {
    console.log('socket', socketId, 'closed');
    delete sockets[socketId];
  });

});

fs.watch("./private/config.json",function(){
    config = JSON.parse(fs.readFileSync("./private/config.json"))
    console.log('Config has changed!'); 
    server.close(function () { console.log('Server is closing!');  });

    for (var socketId in sockets) {
        console.log('socket', socketId, 'destroyed');
        sockets[socketId].destroy();
    }

    server.listen(config.port,config.host,function(){
    console.log("Now listening: "+config.host+ ":" +config.port);
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM