Reload Express.js routes changes without manually restarting server
I tried express-livereload
, but it just reloaded view files.
Should I use another tool, or this one can be configured to watch for my index.js
file which runs the server?
I read that options are the same as node-livereload
, and default for watched files include .js
files.
Any URL you know with a simple configuration?
My main problem is how to setup good development environment for Express.js, and I would like to inspect the variables when I am making a request, is painful to restart each time I make a change in a route.
PS I tried node-inspector
to inspect variables when server handles a request, but it seems node-inspector
is not intended for that, right?
Solution 1:
I think Nodemon has what you're looking for.
Nodemon is a utility that will monitor for any changes in your source and automatically restart your server. Perfect for development.
Example invocation:
nodemon index.js
Solution 2:
I use express.js, normally start server by
npm start
with Nodemon installed, I use
nodemon --exec npm start
Note: nodemon app.js
will NOT work here,
because express.js use start
script
To install nodemon
npm install -g nodemon
Solution 3:
You can livereload both front and backend changes to the browser using 'livereload', 'connect-livereload', and 'nodemon'. Also, this way you don't need Gulp or Grunt. Here's how they work together:
-
livereload
opens a high port and notifies the browser of any changed file -
connect-livereload
monkey patches every served HTML page with a JavaScript snippet that connects to this high port -
nodemon
restarts the server on any changed backend file
Set up livereload in Express
Set up Express to both start livereload server watching the public directory and ping the browser during nodemon
-induced restart:
const livereload = require("livereload");
const connectLivereload = require("connect-livereload");
// open livereload high port and start to watch public directory for changes
const liveReloadServer = livereload.createServer();
liveReloadServer.watch(path.join(__dirname, 'public'));
// ping browser on Express boot, once browser has reconnected and handshaken
liveReloadServer.server.once("connection", () => {
setTimeout(() => {
liveReloadServer.refresh("/");
}, 100);
});
const app = express();
// monkey patch every served HTML so they know of changes
app.use(connectLivereload());
Start Express with Nodemon
Start the server with nodemon, for example, with a dedicated watch script by running npm run watch
.
The key point here is to ignore the public directory that's already being watched by livereload. You can also configure files with non-default extensions, like pug and mustache, to be watched.
"scripts": {
"start": "node ./bin/www",
"watch": "nodemon --ext js,pug --ignore public"
},
You can read a longer explanation in "Refresh front and backend changes to browser with Express, LiveReload and Nodemon."