main
Last change
on this file since d565449 was d565449, checked in by stefan toskovski <stefantoska84@…>, 4 weeks ago |
Update repo after prototype presentation
|
-
Property mode
set to
100644
|
File size:
1.1 KB
|
Rev | Line | |
---|
[d565449] | 1 | 'use strict';
|
---|
| 2 | const path = require('path');
|
---|
| 3 | const resolveFrom = require('resolve-from');
|
---|
| 4 | const parentModule = require('parent-module');
|
---|
| 5 |
|
---|
| 6 | module.exports = moduleId => {
|
---|
| 7 | if (typeof moduleId !== 'string') {
|
---|
| 8 | throw new TypeError('Expected a string');
|
---|
| 9 | }
|
---|
| 10 |
|
---|
| 11 | const parentPath = parentModule(__filename);
|
---|
| 12 |
|
---|
| 13 | const cwd = parentPath ? path.dirname(parentPath) : __dirname;
|
---|
| 14 | const filePath = resolveFrom(cwd, moduleId);
|
---|
| 15 |
|
---|
| 16 | const oldModule = require.cache[filePath];
|
---|
| 17 | // Delete itself from module parent
|
---|
| 18 | if (oldModule && oldModule.parent) {
|
---|
| 19 | let i = oldModule.parent.children.length;
|
---|
| 20 |
|
---|
| 21 | while (i--) {
|
---|
| 22 | if (oldModule.parent.children[i].id === filePath) {
|
---|
| 23 | oldModule.parent.children.splice(i, 1);
|
---|
| 24 | }
|
---|
| 25 | }
|
---|
| 26 | }
|
---|
| 27 |
|
---|
| 28 | delete require.cache[filePath]; // Delete module from cache
|
---|
| 29 |
|
---|
| 30 | const parent = require.cache[parentPath]; // If `filePath` and `parentPath` are the same, cache will already be deleted so we won't get a memory leak in next step
|
---|
| 31 |
|
---|
| 32 | return parent === undefined ? require(filePath) : parent.require(filePath); // In case cache doesn't have parent, fall back to normal require
|
---|
| 33 | };
|
---|
Note:
See
TracBrowser
for help on using the repository browser.