gpt4 book ai didi

Node.js:如何重新加载模块

转载 作者:搜寻专家 更新时间:2023-10-31 22:20:37 26 4
gpt4 key购买 nike

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

我在名为 myapp.php 的外部文件中编写了一堆代码。我启动 NodeJS for windows 并从我键入的解释器窗口:

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

然后我可以在外部模块中使用我的函数和变量。

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

现在,这首先是正常的吗?如何解决这个问题?

P.S.:我在互联网上花了几个小时,并在包括这个在内的许多论坛中进行了搜索。这比其他任何事情都更令人困惑。

谢谢。

最佳答案

some answers here正如评论中所建议的那样。

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

这是一个单行解决方案,您可以将其粘贴到您的 REPL 中,灵感来自对另一个问题的讨论:

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

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

> 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:如何重新加载模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33546880/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com