是否可以在同一个文件中多次使用 "require"?

Is it possible to use "require" on the fly multiple times in the same file?

我想知道是否可以在同一个文件.

中动态使用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: 我将此 post Is it ok to require() the same file multiple times? 红色,但这不是我想要的:我想在 same 文件中要求两次。

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

这是因为每个 require caches the loaded files. You would have to delete the cache before requiring the updated file. Which can be done with the delete operator 因为缓存是一个简单的对象 delete require.cache[require.resolve('/path/to/my/file')].

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