【问题标题】:Is it possible to use "require" on the fly multiple times in the same file?是否可以在同一个文件中多次使用“require”?
【发布时间】:2021-06-11 05:53:25
【问题描述】:

我想知道是否可以在同一个文件中即时使用require 两次。

在第一次和第二次之间,我导入的文件被更新了,我想读取更新后文件的内容。

为了简化问题,我将简单地删除两个require 之间的文件而不是更新它。

fs.removeSync(/path/to/my/file);
const final = require(/path/to/my/file);
// => crash : cannot find module

崩溃是正常的(我删除了文件)。

现在,如果我在删除之前需要该文件,则不会发生崩溃。

const initial = require(/path/to/my/file);
fs.removeSync(/path/to/my/file);
const final = require(/path/to/my/file);
// => No crash !!!

所以,我想require 并没有真正被第二次调用,但我不确定。

我不知道如何第一次读取文件的内容,更新它,然后在同一个文件中再次读取它。

欢迎任何帮助!

PS: 我把这篇文章加红了Is it ok to require() the same file multiple times?,但这不是我想要的:我想在 same 文件中要求两次。

【问题讨论】:

    标签: typescript require


    【解决方案1】:

    为什么第二个要求不崩溃?

    这是因为每个都需要caches 加载的文件。您必须在需要更新文件之前删除缓存。这可以通过delete operator 来完成,因为缓存是一个简单的对象delete require.cache[require.resolve('/path/to/my/file')]

    我不认为这是一个好主意。你为什么不使用fs.readFile呢?

    【讨论】:

    • 是的,太好了!我忘了require 缓存加载的文件。你救了我的命 ! (或者只是我的一天,也许......;))
    • 嗨,对不起,我是新的贡献者,我不知道该怎么做。我认为现在可以了。所以,不要忘记为我的问题投票+1! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-31
    • 2015-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多