Search code examples
typescriptrequire

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


I would like to know if it's possible to use require on the fly two times in the same file.

Between the first and the second time, my imported file was updated, and I want to read the content of the updated file.

To simplify the problem, I will simply delete the file between the two require instead of updating it.

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

The crash is normal (I removed the file).

Now, if I require the file before removing it, there is no crash.

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

So, I suppose that require is not really called a second time, but I'm not sure of it.

I don't find how to read a first time the content of the file, update it and later read it again in the same file.

Any help will be welcome !

PS: I red this post Is it ok to require() the same file multiple times? , but it's not what I want : I want to require two times in the same file.


Solution

  • Why does the second require not crash?

    This is because every 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 since the cache is a simple object delete require.cache[require.resolve('/path/to/my/file')].

    I dont think thats a good idea though. Why are you not using fs.readFile for that?