a blog for those who code

Thursday 16 July 2015

Edit Server Files without Restarting Server in NodeJS

In this post we are going to learn about how to edit server files without restarting nodejs server and see the changes live. Lets say you are doing some live testing of your application and wanted to edit the server file to see the changes without restarting the server every-time then you can use 'node-supervisor' or 'nodules' modules.

Node-Supervisor

According to node-supervisor, it is a little supervisor for nodejs. It runs your program and watches for code changes, so you can have hot-code reloading-ish behavior, without worrying about memory leaks and making sure you clean up all the inter-module references, and without a whole new require system.

Actually node-supervisor can also be used to restart your application if it gets crashed along with restarting when your server file changes. They have a number of options like watch (watch a change in a js file), debug (start server with --debug flag) etc. You can install it using the command npm install supervisor -g.

Example: If suppose I want to watch my example1.js file that any change occured or not after it started we will be doing it with

supervisor -w example1.js

Nodules

According to Nodules, it is an asynchronous module loader for Node that provides URL/HTTP-based module ids, module hot-reloading, and package based module mapping. Nodules implements the CommonJS package.json mappings proposal and automatically analyzes modules references and downloads any dependencies on first access prior to executing modules.

To use reloading feature of Nodules you need to wrap your re-loadable code in a require.reloadable function of Nodules. This function calls a callback function whenever any loaded modules change.

Example : 

require.reloadable(function() {
    //the code which you want to reload when it changes
});

The good thing about Node-Supervisor and Nodules is that they will not do a full restart when any files has changed. Please Like and Share the Blog, if you find it interesting and helpful.

No comments:

Post a Comment