Nodejs auto restart server | NodeJS watch file Changes

nodejs watch
NodeJS Logo(Source: Wikipedia)


When we working with nodejs application manually restarting our application is the tedious task for everyone, so everytime when we working on node application then we may think that How to watch node file changes or just simply watch node file changes right?

So we will see how can we overcome this problem with simple step by using nodemon to watch file changes.

Step 1: Create sample application with the following command:


$ npm init -y #-y for accpeting default configuration

Wrote to /home/ubuntu/dev/blogTutor/package.json:

{
  "name": "blogTutor",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "Vikas",
  "license": "ISC"
}

Step 2: Add Start Script to package.json 


  "scripts": {
    "start": "node src/index.js"
  }

Step 3:  Create our index.js file.

I am adding express.js framework here you can add any framework you want, also add its node modules as well.



#index.js file

const express = require('express');
const app = express();

app.use('/', (req, res) => {
  res.status(200).send('Welcome to NodeJS!');
});

app.listen(5000);

We can run this program using  $ npm run start  command on terminal, Now if you open the browser and open this URL http://localhost:5000/  then you can see following output on the page.

node watch
but if you don't like the message and you want to change it, so you will go to index.js file and then change the message and restart the server, but you don't want to restart it so we will use nodemon to achieve the file watch in nodejs.

Step 4: We will add nodemon development dependency

$ npm install -D nodemon

Step 5: We will add nodemon watch script in package.json 

{
  "scripts": {
    "start": "node src/index.js",
    "dev": "nodemon --watch src src/index.js"
  }
}

Step 6: Run our application with $ npm run dev command  or simply $ nodemon command 

Now, If I do any changes in the index.js file, nodemon will watch the file changes and it will automatically restart the server.


That's it now you can write & test functionality without restarting the server, please comment if you have any difficulties.


Nodejs auto restart server | NodeJS watch file Changes Nodejs auto restart server | NodeJS watch file Changes Reviewed by Vikas Kad on Wednesday, September 26, 2018 Rating: 5

No comments:

Powered by Blogger.