Repository: sindresorhus/clear-module Branch: main Commit: 69df1d4cd77f Files: 18 Total size: 10.9 KB Directory structure: gitextract_e8prwtpn/ ├── .editorconfig ├── .gitattributes ├── .github/ │ └── workflows/ │ └── main.yml ├── .gitignore ├── .npmrc ├── fixture-circular-1.js ├── fixture-circular-2.js ├── fixture-empty.js ├── fixture-match.js ├── fixture-with-dependency.js ├── fixture.js ├── index.d.ts ├── index.js ├── index.test-d.ts ├── license ├── package.json ├── readme.md └── test.js ================================================ FILE CONTENTS ================================================ ================================================ FILE: .editorconfig ================================================ root = true [*] indent_style = tab end_of_line = lf charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true [*.yml] indent_style = space indent_size = 2 ================================================ FILE: .gitattributes ================================================ * text=auto eol=lf ================================================ FILE: .github/workflows/main.yml ================================================ name: CI on: - push - pull_request jobs: test: name: Node.js ${{ matrix.node-version }} runs-on: ubuntu-latest strategy: fail-fast: false matrix: node-version: - 14 - 12 - 10 - 8 steps: - uses: actions/checkout@v6 - uses: actions/setup-node@v6 with: node-version: ${{ matrix.node-version }} - run: npm install - run: npm test ================================================ FILE: .gitignore ================================================ node_modules yarn.lock ================================================ FILE: .npmrc ================================================ package-lock=false ================================================ FILE: fixture-circular-1.js ================================================ 'use strict'; const other = require('./fixture-circular-2'); module.exports = other; ================================================ FILE: fixture-circular-2.js ================================================ 'use strict'; const other = require('./fixture-circular-1'); module.exports = other; ================================================ FILE: fixture-empty.js ================================================ 'use strict'; module.exports = {}; ================================================ FILE: fixture-match.js ================================================ 'use strict'; let i = 0; module.exports = () => ++i; ================================================ FILE: fixture-with-dependency.js ================================================ 'use strict'; // eslint-disable-next-line no-unused-vars const _ = require('./fixture-empty'); const fixture = require('./fixture'); module.exports = () => fixture(); ================================================ FILE: fixture.js ================================================ 'use strict'; let i = 0; module.exports = () => ++i; ================================================ FILE: index.d.ts ================================================ declare const clear: { /** Clear a module from the [cache](https://nodejs.org/api/modules.html#modules_caching). @param moduleId - What you would use with `require()`. @example ``` // foo.ts let i = 0; module.exports = () => ++i; // test.ts import clearModule = require('clear-module'); require('./foo')(); //=> 1 require('./foo')(); //=> 2 clearModule('./foo'); require('./foo')(); //=> 1 ``` */ (moduleId: string): void; /** Clear all modules from the cache. */ all(): void; /** Clear all matching modules from the cache. @param regex - Regex to match against the module IDs. */ match(regex: RegExp): void; /** Clear a single module from the cache non-recursively. No parent or children modules will be affected. This is mostly only useful if you use singletons, where you would want to clear a specific module without causing any side effects. @param moduleId - What you would use with `require()`. */ single(moduleId: string): void; }; export = clear; ================================================ FILE: index.js ================================================ 'use strict'; const path = require('path'); const resolveFrom = require('resolve-from'); const parentModule = require('parent-module'); const resolve = moduleId => { try { return resolveFrom(path.dirname(parentModule(__filename)), moduleId); } catch (_) {} }; const isNativeModule = filePath => path.extname(filePath) === '.node'; const clear = moduleId => { if (typeof moduleId !== 'string') { throw new TypeError(`Expected a \`string\`, got \`${typeof moduleId}\``); } const filePath = resolve(moduleId); if (!filePath) { return; } if (isNativeModule(filePath)) { return; } // Delete itself from module parent if (require.cache[filePath] && require.cache[filePath].parent) { let i = require.cache[filePath].parent.children.length; while (i--) { if (require.cache[filePath].parent.children[i].id === filePath) { require.cache[filePath].parent.children.splice(i, 1); } } } // Remove all descendants from cache as well if (require.cache[filePath]) { const children = require.cache[filePath].children.map(child => child.id); // Delete module from cache delete require.cache[filePath]; for (const id of children) { clear(id); } } }; clear.all = () => { for (const filePath of Object.keys(require.cache)) { if (!isNativeModule(filePath)) { delete require.cache[filePath]; } } }; clear.match = regex => { for (const moduleId of Object.keys(require.cache)) { if (regex.test(moduleId)) { clear(moduleId); } } }; clear.single = moduleId => { if (typeof moduleId !== 'string') { throw new TypeError(`Expected a \`string\`, got \`${typeof moduleId}\``); } const filePath = resolve(moduleId); if (!filePath || isNativeModule(filePath)) { return; } delete require.cache[filePath]; }; module.exports = clear; ================================================ FILE: index.test-d.ts ================================================ import clear = require('.'); clear('my-module'); clear.all(); clear.match(/^.*$/); ================================================ FILE: license ================================================ MIT License Copyright (c) Sindre Sorhus (https://sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: package.json ================================================ { "name": "clear-module", "version": "4.1.3", "description": "Clear a module from the cache", "license": "MIT", "repository": "sindresorhus/clear-module", "funding": "https://github.com/sponsors/sindresorhus", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, "sideEffects": false, "engines": { "node": ">=8" }, "scripts": { "//test": "xo && ava && tsd", "test": "ava" }, "files": [ "index.js", "index.d.ts" ], "keywords": [ "clear", "module", "require", "import", "cache", "uncache", "uncached", "unrequire", "derequire", "delete", "remove", "rm", "fresh" ], "dependencies": { "parent-module": "^2.0.0", "resolve-from": "^5.0.0" }, "devDependencies": { "ava": "^2.1.0", "tsd": "^0.7.2", "xo": "^0.24.0" } } ================================================ FILE: readme.md ================================================ # clear-module > Clear a module from the [cache](https://nodejs.org/api/modules.html#modules_caching) Useful for testing purposes when you need to freshly import a module. ## Install ```sh npm install clear-module ``` ## Usage ```js // foo.js let i = 0; module.exports = () => ++i; ``` ```js const clearModule = require('clear-module'); require('./foo')(); //=> 1 require('./foo')(); //=> 2 clearModule('./foo'); require('./foo')(); //=> 1 ``` ## API ### clearModule(moduleId) #### moduleId Type: `string` What you would use with `require()`. ### clearModule.all() Clear all modules from the cache. ### clearModule.match(regex) Clear all matching modules from the cache. #### regex Type: `RegExp` Regex to match against the module IDs. ### clearModule.single(moduleId) Clear a single module from the cache non-recursively. No parent or children modules will be affected. This is mostly only useful if you use singletons, where you would want to clear a specific module without causing any side effects. #### moduleId Type: `string` What you would use with `require()`. ## Related - [import-fresh](https://github.com/sindresorhus/import-fresh) - Import a module while bypassing the cache - [import-from](https://github.com/sindresorhus/import-from) - Import a module from a given path - [import-cwd](https://github.com/sindresorhus/import-cwd) - Import a module from the current working directory - [import-lazy](https://github.com/sindresorhus/import-lazy) - Import a module lazily ================================================ FILE: test.js ================================================ import fs from 'fs'; import path from 'path'; import test from 'ava'; import clearModule from '.'; const nativeModulePath = path.join(process.cwd(), '.ai-temporary', 'fixture-native.node'); const nonNativeModuleIds = () => Object.keys(require.cache).filter(moduleId => path.extname(moduleId) !== '.node'); const seedNativeModule = () => { if (!fs.existsSync(path.dirname(nativeModulePath))) { fs.mkdirSync(path.dirname(nativeModulePath)); } fs.writeFileSync(nativeModulePath, ''); const nativeModule = { id: nativeModulePath, filename: nativeModulePath, loaded: true, exports: {}, children: [], parent: module }; require.cache[nativeModulePath] = nativeModule; return nativeModule; }; const clearNativeModule = () => { delete require.cache[nativeModulePath]; if (fs.existsSync(nativeModulePath)) { fs.unlinkSync(nativeModulePath); } }; test.after.always(clearNativeModule); test('clearModule()', t => { const id = './fixture'; t.is(require(id)(), 1); t.is(require(id)(), 2); clearModule(id); t.is(require(id)(), 1); }); test('clearModule.all()', t => { t.true(nonNativeModuleIds().length > 0); clearModule.all(); t.is(nonNativeModuleIds().length, 0); }); test('clearModule.match()', t => { const id = './fixture'; const match = './fixture-match'; t.is(require(id)(), 1); t.is(require(match)(), 1); clearModule.match(/match/); t.is(require(id)(), 2); t.is(require(match)(), 1); }); test('clearModule() recursively', t => { clearModule.all(); const id = './fixture-with-dependency'; t.is(require(id)(), 1); t.is(require(id)(), 2); delete require.cache[require.resolve(id)]; t.is(require(id)(), 3); clearModule(id); t.is(require(id)(), 1); }); test('clearModule() recursively, multiple imports', t => { clearModule.all(); const id = './fixture-with-dependency'; t.is(require(id)(), 1); t.is(require(id)(), 2); t.is(require(id)(), 3); clearModule(id); t.is(require(id)(), 1); }); test('clearModule.single()', t => { clearModule.all(); const id = './fixture-with-dependency'; t.is(require(id)(), 1); t.is(require(id)(), 2); clearModule.single(id); t.is(require(id)(), 3); clearModule(id); t.is(require(id)(), 1); }); test.serial('native modules are not cleared', t => { try { let nativeModule = seedNativeModule(); clearModule(nativeModulePath); t.is(require.cache[nativeModulePath], nativeModule); nativeModule = seedNativeModule(); clearModule.single(nativeModulePath); t.is(require.cache[nativeModulePath], nativeModule); nativeModule = seedNativeModule(); clearModule.all(); t.is(require.cache[nativeModulePath], nativeModule); nativeModule = seedNativeModule(); clearModule.match(/fixture-native/); t.is(require.cache[nativeModulePath], nativeModule); const id = './fixture'; require(id); const fixtureModule = require.cache[require.resolve(id)]; nativeModule = seedNativeModule(); fixtureModule.children.push(nativeModule); clearModule(id); t.is(require.cache[nativeModulePath], nativeModule); } finally { clearNativeModule(); } }); test('works with circular dependencies', t => { const id1 = './fixture-circular-1'; require(id1); let parentCalls = 0; let childrenCalls = 0; const {children, parents} = require.cache[require.resolve(id1)]; Object.defineProperty( require.cache[require.resolve(id1)], 'children', { get: () => { childrenCalls++; return children; } } ); Object.defineProperty( require.cache[require.resolve(id1)], 'parent', { get: () => { parentCalls++; return parents; } } ); clearModule(id1); t.is(parentCalls, 1); t.is(childrenCalls, 4); clearModule.all(); });