How to auto-reload files in Node.js while using ESM?
Asked Answered
P

2

11

I understand you can clear files from cache while using CommonJS simply by deleteing from require.cache and requireing the file again. However I've been unable to find an equivalent option when using ESM. Is this possible, and if so how?

Parkway answered 6/3, 2020 at 5:38 Comment(0)
T
6

Reading at esm issues it seems cache is intentionally not exposed.

I'm afraid the answer to your question is simply no.

Turfman answered 6/6, 2020 at 23:29 Comment(0)
J
0

It seems there is a hack using dynamic imports:

const modules = {
  moduleA: async () => await import(`./module-a.js?v=${Date.now()}`)
}

Then use it like:

async function myTest() {
    // module will be reset at each call of the function
    const moduleA = await modules.moduleA() 
}

Unfortunately, like said by @lisonge, the memory of the older module will not be freed up, so keep in mind that it can lead to a memory leak in case of intensive usage.

Here is an issue about it with further details on that technique there

Jarmon answered 9/1, 2023 at 13:3 Comment(2)
The old version modules that were loaded before were unable to remove from memory. Your solution has made the memory occupy more and more under extreme circumstancesScheldt
Thanks @Scheldt for pointing this out, I updated my answer to reflect that 👍Jarmon

© 2022 - 2024 — McMap. All rights reserved.