Node.js: how to reload module

前端 未结 3 1130
走了就别回头了
走了就别回头了 2021-02-04 03:37

I am new to NodeJS so probably I am doing some mistakes.

I have written a bunch of code in an external file called myapp. I start NodeJS for windows and from the interpr

相关标签:
3条回答
  • 2021-02-04 04:37

    I solved this by adding the following above the require statements:

    Object.keys(require.cache).forEach(function(key) { delete require.cache[key] })
    

    Taken from @Dancrumb's comment here

    0 讨论(0)
  • 2021-02-04 04:37

    The other answers (in duplicate and by @mihai) are all correct, but the most direct answer to this specific example, is

    delete require.cache['d:/myapp.js'];
    

    The module is cached in require.cache keyed to the full filename. In this particular case, the full filename (i.e. d:/myapp.js) was used to load, and so the solution to the problem is very straight forward.

    In most cases, however, the full filename is not used or even known. For example, require('fs') would be used to load the filesystem module, but the developer is as a loss to the full and proper filename. As such, require.resolve('fs') will return the filename used as key to cache the module.

    0 讨论(0)
  • 2021-02-04 04:39

    There are some answers here as suggested in the comments.

    However they are not REPL friendly, and might even use extra modules.

    Here is a one line solution that you can paste in your REPL, inspired by the discussion on the other question:

    function nocache(module) {require("fs").watchFile(require("path").resolve(module), () => {delete require.cache[require.resolve(module)]})}
    

    The function will delete your module from the cache each time the file changes. To use it, just paste it in the REPL, call uncache("d:/myapp.js"), then use require normally.

    > function nocache(module) {require("fs").watchFile(require("path").resolve(module), () => {delete require.cache[require.resolve(module)]})}
    > nocache("d:/myapp.js");
    > var myapp = require("d:/myapp.js");
    ......
    > myapp = require("d:/myapp.js");
    ....
    
    0 讨论(0)
提交回复
热议问题