avatar

Lachezar Grigorov

Full stack web and mobile developer

How to config and run express generator to restart the server with nodemon and reload the browser with alallier/reload on code change

Here I will show you how to install, set-up and run the nodemon and reload packages with express generator. 

Let's first install the nodemon. The -g option will install it globally so you can use it with other projects later.

$ npm install -g nodemon

Now you can start the server with your fresh installed nodemon.  According to the express documentation you start the server with: "DEBUG=myapp:* npm start"  So this is how you start the server with the nodemon.

$ nodemon DEBUG=api:* npm start

If you change now some code and refresh the browser you will see immediately the change in your browser because the nodemon has restarted the server for you automatically. 

Next we need to install locally the reload package.

$ npm install reload --save-dev

According to the github page of the reload package. There is only three steps to go.

1.Require the package 

const reload = require('reload')

2.Call the relaod function with the app (middleware) as parameter.


reload(app)

3.Include the /reload/reload.js in your templates. 

 

And here come the tricky part. If you require the package and call the reload function in your  ~bin/www right before the server.listen call (According to the reload documentation, this is the best place for this function to be called.) you will receive reload.js not found message in the browser's console.

 

To handle this error call the reload(app) function right after the app.use('/users', usersRouter) in your app.js file. 

# app.js

const reload = require('reload')

...
app.use('/users', usersRouter)
reload(app)

To refresh the browser on view change you need explicitly to config the nodemon to watch the files with this extensions.

This is very simple. Just create a nodemon.json file in your porject's root folder and put the file extensions you need. In my case I use ejs as templating engine. js, mjs and json are the default extension used by nodemon. 

{
"ext": "js, mjs, json, ejs"
}

Voila, you are ready.