Node.js: how to reload module

谁说胖子不能爱 提交于 2019-12-21 09:07:26

问题


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 interpreter window I type:

var myapp = require('d:/myapp.js');

then I can use my functions and variables in the external module.

The problem is that if I update the code in myapp then the interpreter does not re-read the file and it uses the old version.

Now, is this normal in the first place? How to work around this problem?

P.S.: I have spent hours in internet and searched in many forums including this. It was more confusing then anything else.

Thanks.


回答1:


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");
....


来源:https://stackoverflow.com/questions/33546880/node-js-how-to-reload-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!