diff --git a/content/redirects.yaml b/content/redirects.yaml index a33472897d3..ff9ac3d470d 100644 --- a/content/redirects.yaml +++ b/content/redirects.yaml @@ -901,9 +901,6 @@ - from: /js/s/redirect to: /js/s/redirect-to-url status: 301! -- from: /js/s/require-uncached - to: /js/s/uncached-module-require - status: 301! - from: /js/s/attempt to: /js/s/attempt-invoking-function status: 301! @@ -2911,3 +2908,9 @@ - from: /css/s/triangle to: /css/s/shapes status: 301! +- from: /js/s/require-uncached + to: /js/s/reload-module + status: 301! +- from: /js/s/uncached-module-require + to: /js/s/reload-module + status: 301! diff --git a/content/snippets/js/s/reload-module.md b/content/snippets/js/s/reload-module.md new file mode 100644 index 00000000000..17b7aa75d2c --- /dev/null +++ b/content/snippets/js/s/reload-module.md @@ -0,0 +1,24 @@ +--- +title: Can I reload a module in Node.js? +shortTitle: Reload a module +type: question +language: javascript +tags: [node] +cover: tea-laptop-table +excerpt: Ever wanted to reload a module in Node.js? Here's how you can do it. +dateModified: 2024-05-13 +--- + +If you've ever tried to **reload a module** in Node.js, you might have noticed that it's not as straightforward as you might expect. **Node.js caches modules** after they are loaded, so subsequent `require()` calls return the cached module instead of loading it again. This can be useful for **performance** reasons, but it can also be a hindrance when you want to reload a module. + +Luckily, the require cache can be accessed via `require.cache`, allowing you to manipulate it as needed. Simply using `delete`, you can **remove a module from the cache**, if it exists, allowing you to **load it fresh** the next time you call `require()`. + +```js +const requireUncached = module => { + delete require.cache[require.resolve(module)]; + return require(module); +}; + +const fs = requireUncached('fs'); +// 'fs' will be loaded fresh every time +``` diff --git a/content/snippets/js/s/uncached-module-require.md b/content/snippets/js/s/uncached-module-require.md deleted file mode 100644 index efa734263a5..00000000000 --- a/content/snippets/js/s/uncached-module-require.md +++ /dev/null @@ -1,22 +0,0 @@ ---- -title: Uncached module require -type: snippet -language: javascript -tags: [node] -cover: tea-laptop-table -dateModified: 2020-09-15 ---- - -Loads a module after removing it from the cache (if exists). - -- Use `delete` to remove the module from the cache (if exists). -- Use `require()` to load the module again. - -```js -const requireUncached = module => { - delete require.cache[require.resolve(module)]; - return require(module); -}; - -const fs = requireUncached('fs'); // 'fs' will be loaded fresh every time -```