Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8874819
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T18:49:06+00:00 2026-06-14T18:49:06+00:00

I’ve been trying to figure out this Hot Code Push on Node.js. Basically, my

  • 0

I’ve been trying to figure out this “Hot Code Push” on Node.js. Basically, my main file (that is run when you type node app.js) consists of some settings, configurations, and initializations. In that file I have a file watcher, using chokidar. When I file has been added, I simply require the file. If a file has been changed or updated I would delete the cache delete require.cache[path] and then re-require it. All these modules don’t export anything, it just works with the single global Storm object.

Storm.watch = function() {
    var chokidar, directories, self = this;
    chokidar = require('chokidar');
    directories = ['server/', 'app/server', 'app/server/config', 'public'];
    clientPath = new RegExp(_.regexpEscape(path.join('app', 'client')));
    watcher = chokidar.watch(directories, {
    ignored: function(_path) {
        if (_path.match(/\./)) {
            !_path.match(/\.(js|coffee|iced|styl)$/);
        } else {
            !_path.match(/(app|config|public)/);
        }
    },
    persistent: true
    });


    watcher.on('add', function(_path){
    self.fileCreated(path.resolve(Storm.root, _path));
    //Storm.logger.log(Storm.cliColor.green("File Added: ", _path));
    //_console.info("File Updated");
    console.log(Storm.css.compile('     {name}: {file}', "" +
        "name" +
        "{" +
        "color: white;" +
        "font-weight:bold;" +
        "}" +
        "hr {"  +
        "background: grey" +
        "}")({name: "File Added", file: _path.replace(Storm.root, ""), hr: "=================================================="}));
    });

    watcher.on('change', function(_path){
    _path = path.resolve(Storm.root, _path);
    if (fs.existsSync(_path)) {
        if (_path.match(/\.styl$/)) {
            self.clientFileUpdated(_path);
        } else {
            self.fileUpdated(_path);
        }
    } else {
        self.fileDeleted(_path);
    }
    //Storm.logger.log(Storm.cliColor.green("File Changed: ", _path));
    console.log(Storm.css.compile('     {name}: {file}', "" +
        "name" +
        "{" +
        "color: yellow;" +
        "font-weight:bold;" +
        "}" +
        "hr {"  +
        "background: grey" +
        "}")({name: "File Changed", file: _path.replace(Storm.root, ""), hr: "=================================================="}));
    });

    watcher.on('unlink', function(_path){
    self.fileDeleted(path.resolve(Storm.root, _path));
    //Storm.logger.log(Storm.cliColor.green("File Deleted: ", _path));
    console.log(Storm.css.compile('     {name}: {file}', "" +
        "name" +
        "{" +
        "color: red;" +
        "font-weight:bold;" +
        "}" +
        "hr {"  +
        "background: grey" +
        "}")({name: "File Deleted", file: _path.replace(Storm.root, ""), hr: "=================================================="}));
    });

    watcher.on('error', function(error){
    console.log(error);
    });


};


Storm.watch.prototype.fileCreated = function(_path) {

    if (_path.match('views')) {
    return;
    }

    try {
    require.resolve(_path);
    } catch (error) {
    require(_path);
    }

};


Storm.watch.prototype.fileDeleted = function(_path) {
    delete require.cache[require.resolve(_path)];
};

Storm.watch.prototype.fileUpdated = function(_path) {
    var self = this;
    pattern = function(string) {
    return new RegExp(_.regexpEscape(string));
    };

    if (_path.match(pattern(path.join('app', 'templates')))) {
    Storm.View.cache = {};
    } else if (_path.match(pattern(path.join('app', 'helpers')))) {
    self.reloadPath(path, function(){
        self.reloadPaths(path.join(Storm.root, 'app', 'controllers'));
    });
    } else if (_path.match(pattern(path.join('config', 'assets.coffee')))) {
    self.reloadPath(_path, function(error, config) {
        //Storm.config.assets = config || {};
    });
    } else if (_path.match(/app\/server\/(models|controllers)\/.+\.(?:coffee|js|iced)/)) {
    var isController, directory, klassName, klass;

    self.reloadPath(_path, function(error, config) {
        if (error) {
            throw new Error(error);
        }
    });

    Storm.serverRefresh();

    isController = RegExp.$1 == 'controllers';
    directory    = 'app/' + RegExp.$1;
    klassName = _path.split('/');
    klassName = klassName[klassName.length - 1];
    klassName = klassName.split('.');
    klassName.pop();
    klassName = klassName.join('.');
    klassName = _.camelize(klassName);

    if (!klass) {
        require(_path);
    } else {
        console.log(_path);
        self.reloadPath(_path)
    }

    } else if (_path.match(/config\/routes\.(?:coffee|js|iced)/)) {
    self.reloadPath(_path);
    } else {
    this.reloadPath(_path);
    }

};

Storm.watch.prototype.reloadPath = function(_path, cb) {

    _path = require.resolve(path.resolve(Storm.root, path.relative(Storm.root, _path)));
    delete require.cache[_path];
    delete require.cache[path.resolve(path.join(Storm.root, "server", "application", "server.js"))];
    //console.log(require.cache[path.resolve(path.join(Storm.root, "server", "application", "server.js"))]);
    require("./server.js");

    Storm.App.use(Storm.router);

    process.nextTick(function(){
    Storm.serverRefresh();
    var result = require(_path);
    if (cb) {
        cb(null, result);
    }
    });
};


Storm.watch.prototype.reloadPaths = function(directory, cb) {



};

Some of the code is incomplete / not used as I’m trying a lot of different methods.

What’s Working:

For code like the following:

function run() {
   console.log(123);
}

Works perfectly. But any asynchronous code fails to update.

Problem = Asynchronous Code

app.get('/', function(req, res){
   // code here..
});

If I then update the file when the nodejs process is running, nothing happens, though it goes through the file watcher and the cache is deleted, then re-established. Another instance where it doesn’t work is:

// middleware.js
function hello(req, res, next) {
  // code here...
}

// another file:
app.use(hello);

As app.use would still be using the old version of that method.

Question:

How could I fix the problem? Is there something I’m missing?

Please don’t throw suggestions to use 3rd party modules like forever. I’m trying to incorporate the functionality within the single instance.

EDIT:

After studying meteors codebase (there’s surprisingly little resources on “Hot Code Push” in node.js or browser.) and tinkering around with my own implementation I’ve successfully made a working solution. https://github.com/TheHydroImpulse/Refresh.js . This is still at an early stage of development, but it seems solid right now. I’ll be implementing a browser solution too, just for sake of completion.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T18:49:07+00:00Added an answer on June 14, 2026 at 6:49 pm

    Deleting require‘s cache doesn’t actually “unload” your old code, nor does it undo what that code did.

    Take for example the following function:

    var callbacks=[];
    registerCallback = function(cb) {
        callbacks.push(cb);
    };
    

    Now let’s say you have a module that calls that global function.

    registerCallback(function() { console.log('foo'); });
    

    After your app starts up, callbacks will have one item. Now we’ll modify the module.

    registerCallback(function() { console.log('bar'); });
    

    Your ‘hot patching’ code runs, deletes the require.cached version and re-loads the module.

    What you must realize is that now callbacks has two items. First, it has a reference to the function that logs foo (which was added on app startup) and a reference to the function that logs bar (which was just added).

    Even though you deleted the cached reference to the module’s exports, you can’t actually delete the module. As far as the JavaScript runtime is concerned, you simply removed one reference out of many. Any other part of your application can still be hanging on to a reference to something in the old module.

    This is exactly what is happening with your HTTP app. When the app first starts up, your modules attach anonymous callbacks to routes. When you modify those modules, they attach a new callback to the same routes; the old callbacks are not deleted. I’m guessing that you’re using Express, and it calls route handlers in the order they were added. Thus, the new callback never gets a chance to run.


    To be honest, I wouldn’t use this approach to reloading you app on modification. Most people write app initialization code under the assumption of a clean environment; you’re violating that assumption by running initialization code in a dirty environment – that is, one which is already up and running.

    Trying to clean up the environment to allow your initialization code to run is almost certainly more trouble than it’s worth. I’d simply restart the entire app when your underlying files have changed.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
I know there's a lot of other questions out there that deal with this
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I have this code to decode numeric html entities to the UTF8 equivalent character.
I am trying to render a haml file in a javascript response like so:
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString
I'm trying to convert HTML to plain text. I get many &\#8217; &\#8220; etc.
I'm trying to create an if statement in PHP that prevents a single post
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.