How can I edit on my server files without restarting nodejs when i want to see the changes?

后端 未结 9 1122
天命终不由人
天命终不由人 2020-12-02 09:50

I\'m trying to setup my own nodejs server, but I\'m having a problem. I can\'t figure out how to see changes to my application without restarting it. Is there a way to edit

9条回答
  •  猫巷女王i
    2020-12-02 10:18

    There should be some emphasis on what's happening, instead of just shotgunning modules at the OP. Also, we don't know that the files he is editing are all JS modules or that they are all using the "require" call. Take the following scenarios with a grain of salt, they are only meant to describe what is happening so you know how to work with it.

    1. Your code has already been loaded and the server is running with it

      • SOLUTION You need to have a way to tell the server what code has changed so that it can reload it. You could have an endpoint set up to receive a signal, a command on the command line or a request through tcp/http that will tell it what file changed and the endpoint will reload it.

        //using Express
        var fs = require('fs');
        app.get('reload/:file', function (req, res) {
            fs.readfile(req.params.file, function (err, buffer) {
                //do stuff...
            });
        });
        
    2. Your code may have "require" calls in it which loads and caches modules

      • SOLUTION since these modules are cached by require, following the previous solution, you would need a line in your endpoint to delete that reference

        var moduleName = req.params.file;
        delete require.cache[moduleName];
        require('./' + moduleName);
        

    There's a lot of caveats to get into behind all of this, but hopefully you have a better idea of what's happening and why.

提交回复
热议问题