You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

192 lines
7.7 KiB

  1. # Stealthy-Require
  2. [![Build Status](https://img.shields.io/travis/analog-nico/stealthy-require/master.svg?style=flat-square)](https://travis-ci.org/analog-nico/stealthy-require)
  3. [![Coverage Status](https://img.shields.io/coveralls/analog-nico/stealthy-require.svg?style=flat-square)](https://coveralls.io/r/analog-nico/stealthy-require)
  4. [![Dependency Status](https://img.shields.io/david/analog-nico/stealthy-require.svg?style=flat-square)](https://david-dm.org/analog-nico/stealthy-require)
  5. This is probably the closest you can currently get to require something in node.js with completely bypassing the require cache.
  6. `stealthy-require` works like this:
  7. 1. It clears the require cache.
  8. 2. It calls a callback in which you require your module(s) without the cache kicking in.
  9. 3. It clears the cache again and restores its old state.
  10. The restrictions are:
  11. - [Native modules cannot be required twice.](https://github.com/nodejs/node/issues/5016) Thus this module bypasses the require cache only for non-native (e.g. JS) modules.
  12. - The require cache is only bypassed for all operations that happen synchronously when a module is required. If a module lazy loads another module at a later time that require call will not bypass the cache anymore.
  13. This means you should have a close look at all internal require calls before you decide to use this library.
  14. ## Installation
  15. [![NPM Stats](https://nodei.co/npm/stealthy-require.png?downloads=true)](https://npmjs.org/package/stealthy-require)
  16. This is a module for node.js and is installed via npm:
  17. ``` bash
  18. npm install stealthy-require --save
  19. ```
  20. ## Usage
  21. Let's say you want to bypass the require cache for this require call:
  22. ``` js
  23. var request = require('request');
  24. ```
  25. With `stealthy-require` you can do that like this:
  26. ``` js
  27. var stealthyRequire = require('stealthy-require');
  28. var requestFresh = stealthyRequire(require.cache, function () {
  29. return require('request');
  30. });
  31. ```
  32. The require cache is bypassed for the module you require (i.e. `request`) as well as all modules the module requires (i.e. `http` and many more).
  33. Sometimes the require cache shall not be bypassed for specific modules. E.g. `request` is required but `tough-cookie` – on which `request` depends on – shall be required using the regular cache. For that you can pass two extra arguments to `stealthyRequire(...)`:
  34. - A callback that requires the modules that shall be required without bypassing the cache
  35. - The `module` variable
  36. ``` js
  37. var stealthyRequire = require('stealthy-require');
  38. var requestFresh = stealthyRequire(require.cache, function () {
  39. return require('request');
  40. },
  41. function () {
  42. require('tough-cookie'); // No return needed
  43. // You can require multiple modules here
  44. }, module);
  45. ```
  46. ## Usage with Module Bundlers
  47. - [Webpack](https://webpack.github.io) works out-of-the-box like described in the [Usage section](#usage) above.
  48. - [Browserify](http://browserify.org) does not expose `require.cache`. However, as of `browserify@13.0.1` the cache is passed as the 6th argument to CommonJS modules. Thus you can pass this argument instead:
  49. ``` js
  50. // Tweak for Browserify - using arguments[5] instead of require.cache
  51. var requestFresh = stealthyRequire(arguments[5], function () {
  52. return require('request');
  53. });
  54. ```
  55. ## Preventing a Memory Leak When Repeatedly Requiring Fresh Module Instances in Node.js
  56. If you are using `stealthy-require` in node.js and repeatedly require fresh module instances the `module.children` array will hold all module instances which prevents unneeded instances to be garbage collected.
  57. Assume your code calls `doSomething()` repeatedly.
  58. ``` js
  59. var stealthyRequire = require('stealthy-require');
  60. function doSomething() {
  61. var freshInstance = stealthyRequire(require.cache, function () {
  62. return require('some-module');
  63. });
  64. return freshInstance.calc();
  65. }
  66. ```
  67. After `doSomething()` returns `freshInstance` is not used anymore but won’t be garbage collected because `module.children` still holds a reference. The solution is to truncate `module.children` accordingly:
  68. ``` js
  69. var stealthyRequire = require('stealthy-require');
  70. function doSomething() {
  71. var initialChildren = module.children.slice(); // Creates a shallow copy of the array
  72. var freshInstance = stealthyRequire(require.cache, function () {
  73. return require('some-module');
  74. });
  75. module.children = initialChildren;
  76. return freshInstance.calc();
  77. }
  78. ```
  79. The `slice` operation removes all new `module.children` entries created during the `stealthyRequire(...)` call and thus `freshInstance` gets garbage collected after `doSomething()` returns.
  80. ## Technical Walkthrough
  81. ``` js
  82. // 1. Load stealthy-require
  83. var stealthyRequire = require('stealthy-require');
  84. // This does nothing but loading the code.
  85. // It has no side-effects like patching the module loader or anything.
  86. // Any regular require works as always.
  87. var request1 = require('request');
  88. // 2. Call stealthyRequire with passing the require cache and a callback.
  89. var requestFresh = stealthyRequire(require.cache, function () {
  90. // 2a. Before this callback gets called the require cache is cleared.
  91. // 2b. Any require taking place here takes place on a clean require cache.
  92. // Since the require call is part of the user's code it also works with module bundlers.
  93. return require('request');
  94. // Anything returned here will be returned by stealthyRequire(...).
  95. // 2c. After this callback gets called the require cache is
  96. // - cleared again and
  97. // - restored to its old state before step 2.
  98. });
  99. // Any regular require again works as always.
  100. // In this case require returns the cached request module instance.
  101. var request2 = require('request');
  102. // And voilà:
  103. request1 === request2 // -> true
  104. request1 === requestFresh // -> false
  105. ```
  106. ## Contributing
  107. To set up your development environment for `stealthy-require`:
  108. 1. Clone this repo to your desktop,
  109. 2. in the shell `cd` to the main folder,
  110. 3. hit `npm install`,
  111. 4. hit `npm install gulp -g` if you haven't installed gulp globally yet, and
  112. 5. run `gulp dev`. (Or run `node ./node_modules/.bin/gulp dev` if you don't want to install gulp globally.)
  113. `gulp dev` watches all source files and if you save some changes it will lint the code and execute all tests. The test coverage report can be viewed from `./coverage/lcov-report/index.html`.
  114. If you want to debug a test you should use `gulp test-without-coverage` to run all tests without obscuring the code by the test coverage instrumentation.
  115. ## Change History
  116. - v1.1.1 (2017-05-08)
  117. - Fix that stops `undefined` entries from appearing in `require.cache` *(Thanks to @jasperjn from reporting this in [issue #4](https://github.com/analog-nico/stealthy-require/issues/4))*
  118. - v1.1.0 (2017-04-25)
  119. - Added ability to disable bypassing the cache for certain modules *(Thanks to @novemberborn for suggesting this in [issue #3](https://github.com/analog-nico/stealthy-require/issues/3))*
  120. - Added section in README about a [potential memory leak](#preventing-a-memory-leak-when-repeatedly-requiring-fresh-module-instances-in-nodejs) *(Thanks to @Flarna and @novemberborn for bringing that up in [issue #2](https://github.com/analog-nico/stealthy-require/issues/2))*
  121. - Performance optimizations *(Thanks to @jcready for [pull request #1](https://github.com/analog-nico/stealthy-require/pull/1))*
  122. - v1.0.0 (2016-07-18)
  123. - **Breaking Change:** API completely changed. Please read the [Usage section](#usage) again.
  124. - Redesigned library to support module bundlers like [Webpack](https://webpack.github.io) and [Browserify](http://browserify.org)
  125. - v0.1.0 (2016-05-26)
  126. - Initial version
  127. ## License (ISC)
  128. In case you never heard about the [ISC license](http://en.wikipedia.org/wiki/ISC_license) it is functionally equivalent to the MIT license.
  129. See the [LICENSE file](LICENSE) for details.