Node.js — ESM Bypass Cache for Dynamic Imports

The JavaScript and Node.js ecosystem has a large package ecosystem. You’re typically installing dependencies using a package manager, like npm. Another option is to write the needed code yourself. No matter which direction you’re choosing, your application needs to load the needed files from your own project files or files of a package.

This tutorial shows you how to bypass the ESM import cache when dynamically loading files with the import function.

Node.js Series Overview

  1. String Replace All Appearances
  2. Remove All Whitespace From a String in JavaScript
  3. Generate a Random ID or String in Node.js or JavaScript
  4. Remove Extra Spaces From a String in JavaScript or Node.js
  5. Remove Numbers From a String in JavaScript or Node.js
  6. Get the Part Before a Character in a String in JavaScript or Node.js
  7. Get the Part After a Character in a String in JavaScript or Node.js
  8. How to Check if a Value is a String in JavaScript or Node.js
  9. Check If a String Includes All Strings in JavaScript/Node.js/TypeScript
  10. Check if a Value is a String in JavaScript and Node.js
  11. Limit and Truncate a String to a Given Length in JavaScript and Node.js
  12. Split a String into a List of Characters in JavaScript and Node.js
  13. How to Generage a UUID in Node.js
  14. Reverse a String in JavaScript or Node.js
  15. Split a String into a List of Lines in JavaScript or Node.js
  16. Split a String into a List of Words in JavaScript or Node.js
  17. Detect if a String is in camelCase Format in Javascript or Node.js
  18. Check If a String Is in Lowercase in JavaScript or Node.js
  19. Check If a String is in Uppercase in JavaScript or Node.js
  20. Get the Part After First Occurrence in a String in JavaScript or Node.js
  21. Get the Part Before First Occurrence in a String in JavaScript or Node.js
  22. Get the Part Before Last Occurrence in a String in JavaScript or Node.js
  23. Get the Part After Last Occurrence in a String in JavaScript or Node.js
  24. How to Count Words in a File
  25. How to Shuffle the Characters of a String in JavaScript or Node.js
  26. Append Characters or Words to a String in JavaScript or Node.js
  27. Check if a String is Empty in JavaScript or Node.js
  28. Ensure a String Ends with a Given Character in JavaScript or Node.js
  29. Left-Trim Characters Off a String in JavaScript or Node.js
  30. Right-Trim Characters Off a String in JavaScript or Node.js
  31. Lowercase the First Character of a String in JavaScript or Node.js
  32. Uppercase the First Character of a String in JavaScript or Node.js
  33. Prepend Characters or Words to a String in JavaScript or Node.js
  34. Check if a String is a Number
  35. Convert a String to Buffer
  36. Prevent Line Breaks in String Template Literals
  37. How to Implement a Custom `toString` Method
  38. What Is `Symbol.toStringTag` and How to Use It (Coming soon)

Import Module or File Without Cache

Node.js supports import() expressions to asynchronously and dynamically load an ECMAScript module into the current environment. A dynamic import() call is similar to a top-level import with the import … from 'package-name' notation.

The import function comes with an internal module cache. This cache allows you to keep a loaded module at hand and not load it again when requested. The cache speeds up module loading in your environment when requesting the same module more than once in your application.

There can be a situation where you intentionally want to re-import a module, without using the cache. The cache is not publicly available. You can’t manually delete a module entry to force reload it. You must use another way.

To import a module and ignore the internal ECMAScript cache, append a random query parameter. Why is this working? The import function uses a URL for imports and if the URL to import doesn’t match an entry in the cache, it’s loaded without the cache:

const modulePath = './router/routes.js'

const imported = await import(`${modulePath}?imported=${Date.now()}`)  

You can create a helper function to import ECMAScript modules freshly, without reading already imported modules from the internal cache. Here’s the sample code that appends a query parameter with the current timestamp onto the import module path:

/**
 * Freshly imports the ECMAScript module from the given `modulePath`, without using the cache.
 */
export async function importBypassCache(modulePath) {  
  const modulePath = `${modulePath}?imported=${Date.now()}`
  const imported = await import(modulePath)

  return imported.default
}

await importBypassCache('./router/routes.js')  
await importBypassCache('./router/routes.js')  

Be Aware of a Memory Leak

You can bypass the ECMAScript module cache by tacking a query parameter onto the import URL. Importing the same module more than once, but with different URLs will load the same module into memory again, and again, …. Old module versions, possibly never used again, stay in the cache and memory.

There’s an existing Node.js issue related to this problem. A developer pointed out this memory leak issue while transitioning the Mocha testing framework to ESM.

Enjoy!


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.