var http = require("http"); var fs = require("fs"); var server = http.createServer(function (request, response) { response.writeHead(200, { "Content-type": "text/html" }) var stream = fs.createReadStream(__dirname + "/index.html", "utf-8"); stream.pipe(response); }); server.listen(4000, "127.0.0.1"); server.on("error", function (e) { if (e.code == "EADDRINUSE") { console.log("in error") setTimeout(function () { server.close(); server.listen(4000, "127.0.0.1") }, 1000); } }) console.log("server has started")