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

后端 未结 9 1116
天命终不由人
天命终不由人 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条回答
  •  天命终不由人
    2020-12-02 10:28

    if you would like to reload a module without restarting the node process, you can do this by the help of the watchFile function in fs module and cache clearing feature of require:

    Lets say you loaded a module with a simple require:

    var my_module = require('./my_module');
    

    In order to watch that file and reload when updated add the following to a convenient place in your code.

    fs.watchFile(require.resolve('./my_module'), function () {
        console.log("Module changed, reloading...");
        delete require.cache[require.resolve('./my_module')]
        my_module = require('./my_module');
    });
    

    If your module is required in multiple files this operation will not affect other assignments, so keeping module in a global variable and using it where it is needed from global rather than requiring several times is an option. So the code above will be like this:

    global.my_module = require ('./my_module');
    //..
    fs.watchFile(require.resolve('./my_module'), function () {
        console.log("Module changed, reloading...");
        delete require.cache[require.resolve('./my_module')]
        global.my_module = require('./my_module');
    });
    

提交回复
热议问题