を使用してファイルの変更をconfigの場合は、以下のように私はNodeJSで書かれたシンプルで働くWebサーバーを持っている:今、私は私のウェブサーバが再起動したときに、ポート番号の新しいポートを聞きたい再起動、WebサーバーNodeJS
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);
}
});
});
設定ファイルの変更。だから私は、コードの下に追加します。
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);
});
});
これは正常に動作し、私は、configファイルのポートを変更したときに、私は新しいポート上で私のWebサーバにアクセスすることができます。ただし、以前のポートでもアクセスできます。新しいポートを聞く前に、前のポートでWebサーバーを閉じていると思っていました。私は何が欠けていますか?
私はあなたの助けに感謝:)
私の2セント、説明https://nodejs.org/api/net.html#net_server_close_callbackとして、それは新しい接続を受け付けを停止し、既存の接続を維持します。 –
私は、 'keep-alive'がサーバに接続を閉じないようにさせていると思います。 –
なぜノーデモンを使用しないのですか – UchihaItachi