Kirk Ouimet
Kirk Ouimet

Reputation: 28354

Any repercussions to requiring the same file twice in node.js?

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

require('myclass.js');
require('myclass.js');

Upvotes: 9

Views: 6243

Answers (3)

Elias Zamaria
Elias Zamaria

Reputation: 101053

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

Upvotes: 3

JohnnyHK
JohnnyHK

Reputation: 311835

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

Upvotes: 16

user3467440
user3467440

Reputation:

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?

Upvotes: 0

Related Questions