Auto Restart Server With NoDemon: Node.js

Advertisement:

As we have already started using Web Framework of Node.js i.e., Express, we’ll be building considerably large web applications, and it needs us to edit the files often. We need to restart the server every time we save changes to main application file. This would start consuming lot of time and sometimes we may forget to restart the server and may think that our application file has bugs, as it doesn’t reflect on the browser!

node-server-auto-restart

To solve this issue, we could make use of some dependency modules which listens to the changes we saved to these main node application file and restarts the server automatically by itself.

Package File
package.json

1
2
3
4
5
6
7
8
9
10
11
12
13
{
  "name": "route-app",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node app.js"
  },
  "dependencies": {
    "express": "3.4.0",
    "jade": "*",
    "nodemon": "*"
  }
}

As you can see we have added nodemon as a dependency to our application.

Local Module Installation
installation of dependencies

1
npm install

This installs all the dependencies listed in package.json file. If some of the dependencies are already installed, it ignores such things and installs the new dependencies listed in package.json file.

1
nodemon app.js

Since NoDemon is a local module to our application, you can not execute your node application using above command. However there is a simple work around for this:

Change starting point of execution
package.json

1
2
3
4
5
6
7
8
9
10
11
12
13
{
  "name": "route-app",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "nodemon app.js"
  },
  "dependencies": {
    "express": "3.4.0",
    "jade": "*",
    "nodemon": "*"
  }
}

In above file we change the value of start from node app.js to nodemon app.js

Execution Command
Command Prompt / Console

1
npm start

Now this command would trigger the nodemon app.js present inside package.json file, which is local to our specific application.

Auto Restart Server With NoDemon: Node.js


You need to a flashplayer enabled browser to view this YouTube video

YouTube Link: http://www.youtube.com/watch?v=eMZZa1nh8iY [Watch the Video In Full Screen.]



Now whenever we make changes to app.js file, and hit save, nodemon object listens to the new changes we saved, and restarts the server. This way we save a lot of time while in development mode, and directly see the changes reflect on our web browser almost immediately upon refreshing the web browser.

Note: Changes to files in public directory and the .jade files doesn’t require a server restart to reflect on the browser. These are files which are simply rendered upon calling, so whatever is present in these files are [compiled and] shown whenever there is a request to it.

Advertisements

Leave a Reply

Your email address will not be published. Required fields are marked *