admin管理员组

文章数量:1353662

Given an ESM Node.js v23.10.0 project (package.json contains "type":"module"), I want to require a file, then delete its cache, and require it again so that its source runs again.

I tried this:

mod.js

console.log('in mod.ts')

testcase.js

import { createRequire } from 'module'
const require = createRequire(import.meta.url)

require('./mod.js')

const key = Object.keys(require.cache)[0]
delete require.cache[key]

require('./mod.js')

There are ways to do this in a CJS project such as this answer, but I can't figure out how to do it in an ESM project.

I expected to see the console log printed twice, but it only prints once.

Is there a way to successfully uncache a module and reload its body in this test case?

Given an ESM Node.js v23.10.0 project (package.json contains "type":"module"), I want to require a file, then delete its cache, and require it again so that its source runs again.

I tried this:

mod.js

console.log('in mod.ts')

testcase.js

import { createRequire } from 'module'
const require = createRequire(import.meta.url)

require('./mod.js')

const key = Object.keys(require.cache)[0]
delete require.cache[key]

require('./mod.js')

There are ways to do this in a CJS project such as this answer, but I can't figure out how to do it in an ESM project.

I expected to see the console log printed twice, but it only prints once.

Is there a way to successfully uncache a module and reload its body in this test case?

Share Improve this question edited Mar 31 at 22:06 user29889977 asked Mar 31 at 16:36 user29889977user29889977 1492 silver badges6 bronze badges 6
  • @HeikoTheißen I updated it to clarify how it's a unique new question. – user29889977 Commented Mar 31 at 16:43
  • @jabaa I clarified. – user29889977 Commented Mar 31 at 16:56
  • The question doesn't mention node version, which is relevant – Estus Flask Commented Mar 31 at 20:25
  • If you want to run code multiple times, put it in a function not at the top level of a module. (Of course you could still eval(readFileSync(…)) instead of require if that's your goal, but I doubt that). – Bergi Commented Mar 31 at 22:05
  • @EstusFlask added version – user29889977 Commented Mar 31 at 22:06
 |  Show 1 more comment

1 Answer 1

Reset to default 2

This relies on require(esm) feature that previously was experimental and now is enabled in Node 23 by default. This would cause ERR_REQUIRE_ESM error in previous Node versions.

mod.js with default extension and type: module is evaluated as ES module with respective semantics regardless of how it's imported, while require.cache is applied to CommonJS modules only.

In order to make it work as expected in Node project with type: module mod.js needs to be evaluated as CommonJS, so it must be renamed to mod.cjs.

本文标签: javascriptHow do you uncache a module in Nodejs when using createRequireStack Overflow