Node.js:如何重新加载模块 [英] Node.js: how to reload module

查看:182
本文介绍了Node.js:如何重新加载模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是NodeJS的新手,所以我可能在犯一些错误.

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

我已经在名为myapp的外部文件中编写了一堆代码.我启动Windows的NodeJS,并在解释器窗口中键入:

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.

问题是,如果我更新myapp中的代码,则解释器不会重新读取文件,而是使用旧版本.

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 .:我已经在互联网上度过了数小时,并在许多论坛中进行过搜索(包括此内容).比其他任何事情都更令人困惑.

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

谢谢.

推荐答案

这里有一些答案,如评论中所建议.

但是它们不是REPL友好的,甚至可能使用额外的模块.

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

这里是一个单行解决方案,您可以在另一个问题的讨论中得到启发,将其粘贴到REPL中:

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)]})}

该功能将在每次文件更改时从缓存中删除您的模块. 要使用它,只需将其粘贴到REPL中,调用uncache("d:/myapp.js"),然后正常使用require.

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

这篇关于Node.js:如何重新加载模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆