Javascript 需要多次

Javascript 需要多次,javascript,node.js,Javascript,Node.js,文件my_script.js: (function() { console.log("IMPORTED"); })(); module.exports = () => console.log("Imported"); require('myscript.js')(); // note the () at the end which actually calls the function require('myscript.js')(); // note the () at th

文件
my_script.js

(function() {
    console.log("IMPORTED");
})();
module.exports = () => console.log("Imported");
require('myscript.js')(); // note the () at the end which actually calls the function
require('myscript.js')(); // note the () at the end which actually calls the function
调用此文件(
run_me.js
)将导致导入的
打印两次:

require("./my_script");
require("./my_script");
但是它只打印一次

如何更改
run_me.js
,以便将导入的
打印到控制台两次

假设对于这个问题,无法对
my_script.js
require()
缓存其结果。因此,第一次需要一个模块时,它的初始化代码就会运行。之后,缓存只返回module.exports的值,而不再次运行初始化代码。这是node.js模块非常理想的功能

如果希望每次都运行代码,则应导出一个函数,以便在需要时调用,如下所示:

delete require.cache[require.resolve('./my_script')];
您的模块:

module.exports = function() {
    console.log("IMPORTED");
}
每次都需要它并运行代码

require("./my_script")();
require("./my_script")();
另外,请注意,没有理由在模块中使用IIFE。node.js模块已经自动包装在一个私有函数中,因此您无需再次执行


正如您现在在评论中所说(但您的问题没有直接说明),如果您根本不想编辑my_脚本(这是解决此问题的错误方法),那么您必须在再次要求之前从node.js缓存中删除模块,可以这样做:

delete require.cache[require.resolve('./my_script')];

我不建议将此作为解决方案。这不是在node.js中编写代码的正确方法。这是一个破解方法。

您可以使用此软件包,它是一个npm模块,每次都会清除缓存并从源文件中加载模块


我认为不修改
myscript.js
文件是不可能的。特别是当你展示它时,它不会输出任何东西

它将在您第一次需要它时执行(这就是为什么您会看到“Imported”一次),但是在以后调用require时不会发生任何事情,因为返回的“cached”值(即
module.exports
)为空

下面是一个我认为您想要的示例(除了myscript.js已被修改)。最大的区别在于,在原始的
myscript.js
文件中,函数实际上是执行的,而在下面的示例中,函数只是定义的,然后在
run_me.js
文件中的
require
调用中实际执行

文件
myscript.js

(function() {
    console.log("IMPORTED");
})();
module.exports = () => console.log("Imported");
require('myscript.js')(); // note the () at the end which actually calls the function
require('myscript.js')(); // note the () at the end which actually calls the function
文件
运行_me.js

(function() {
    console.log("IMPORTED");
})();
module.exports = () => console.log("Imported");
require('myscript.js')(); // note the () at the end which actually calls the function
require('myscript.js')(); // note the () at the end which actually calls the function

如果您使用jest并希望每次都运行代码进行测试,则可以使用:


为什么要导入两次?您可以
my_script
打印两个可能的副本,即此节点、网页包、其他?@andrewgi我不想编辑
my_script
。请原谅我one@AndyRayNodejs,检查问题标签幸运的是,我被错误的方法困住了。我很感激你的回答。为什么糟糕的方法如此糟糕?@JoshMcGee-如果你希望一个模块是可变的(反复运行),那么只需设计一个从该函数导出的函数,并根据需要多次调用它。从缓存中删除它只是为了再次运行它是一种攻击。这就是模块的工作原理,不能保证较新的ESM模块能够以这种方式工作。此外,如果您希望模块具有特定功能,则将该功能构建到模块本身中,而不是试图通过黑客攻击使其再次运行其初始化代码。此解决方案对我有效: