ElJay
ElJay

Reputation: 367

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

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?

Upvotes: 11

Views: 1714

Answers (2)

TOPKAT
TOPKAT

Reputation: 8688

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

Upvotes: 0

Daniele Ricci
Daniele Ricci

Reputation: 15837

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

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

Upvotes: 6

Related Questions