NodeJS close previous server port before creating new server
Here, I am doing some development and testing so each time I change something I've to exit server and do changes and start new server.
For first time when I run command node server.js
file it works like a charm but when I exit it and do some changes and start again it gives me this error in console :
throw er; // Unhandled 'error' event
I searched a bit about it and I found that this error comes when that port is already in used and when I changed port name and then start it works fine.
var express = require("express");
var app = express();
var port = 3702;
app.get("/", function(req, res){
console.log(req);
res.send("It works!");
});
app.on('error', function(err) {
console.log(err);
});
app.listen(port);
console.log("Listening on port " + port);
Changing the port number for every change you make to the server and starting a new process isn't good practice. From the way you phrased the question is seems you want to do this for development purposes to test changes as you go. There are tools, like nodemon, that help you do exactly this. They'll watch the files in your project and any change will trigger a restart of the server in the same port.
Using nodemon
is as simple as installing it through npm: npm install -g nodemon
and then start your application using nodemon
instead of node
.