Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

node.js

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

require('myclass.js');
require('myclass.js');
like image 977
Kirk Ouimet Avatar asked Jul 12 '14 03:07

Kirk Ouimet


2 Answers

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

like image 198
JohnnyHK Avatar answered Sep 28 '22 11:09

JohnnyHK


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
like image 39
Elias Zamaria Avatar answered Sep 28 '22 13:09

Elias Zamaria