9

Will I run into any problems if I require the same file twice?

require('myclass.js');
require('myclass.js');
Kirk Ouimet
  • 27,280
  • 43
  • 127
  • 177

3 Answers3

16

Absolutely none. Modules are cached the first time they are loaded so the second call is just a no-op.

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • Unless the module does something on require, which is probably bad practice anyways.. – knownasilya Jul 13 '14 at 00:27
  • @Knownasilya The code in the required module is only run the first time `require` is called, or were you referencing something else? – JohnnyHK Jul 13 '14 at 02:29
  • Even if you have an IIFE in your module? So it caches the result and gives you that on subsequent calls? – knownasilya Jul 13 '14 at 03:40
  • 1
    @Knownasilya Right, the module's `module.exports` object created in the first call is cached and also returned in the second call. There's nothings special about IIFEs in this regard. – JohnnyHK Jul 13 '14 at 05:28
3

I discovered a caveat, resulting from the fact that requiring twice is a no-op: requiring a file, mutating the object returned by that file, and requiring the file again will not undo the mutations.

Example:

let path;
path = require('path');
console.log(path.asdf);

path.asdf = 'foo';
console.log(path.asdf);

path = require('path');
console.log(path.asdf);

This produces the following output:

undefined
foo
foo
Elias Zamaria
  • 96,623
  • 33
  • 114
  • 148
0

No, you shouldn't run into any problems. The module system node uses won't have global problems, if that was your question. The real question is... why would u want to require twice?

  • 1
    I'm dynamically including files so there is a chance I may require the same one twice – Kirk Ouimet Jul 12 '14 at 03:44
  • Are you trying to load modules dynamically depending on the outcome of a function? If so here is what I think will help http://stackoverflow.com/questions/10914751/loading-node-js-modules-dynamically-based-on-route –  Jul 12 '14 at 03:53
  • 2
    I would like to require the same file twice, because the file itself includes a function, that I'm mocking in my tests. However I have different tests which mock the function differently, and it doesn't work because the file can only be included once. – David Torres Jul 13 '18 at 20:20
  • @DavidTorres, you can use jest.isolateModules for it, see https://stackoverflow.com/questions/45571816/reset-single-module-with-jest – ChelowekKot Apr 27 '21 at 09:23