Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does module.exports in node js create a shallow copy or deep copy of the exported objects or functions?

For example,

If I have 2 modules try1.js and try2.js

try1.js
   module.exports.msg = "hello world";

try2.js
   try1 = require('./try1');
   try1.msg = "changed message";

Does the change in the contents of msg made in try2.js affect try value of msg in try1.js?

like image 372
Ullas Kashyap Avatar asked Dec 18 '22 06:12

Ullas Kashyap


1 Answers

There is no copy at all made. module.exports is an object and that object is shared directly. If you modify properties on that object, then all who have loaded that module will see those changes.

Does the change in the contents of msg made in try2.js affect try value of msg in try1.js?

Yes, it does. There are no copies. The exports object is shared directly. Any changes you make to that exported object will be seen by all who are using that module.

FYI, a module could use Object.freeze(module.exports) to prevent changes to that object after the desired properties are added.

like image 131
jfriend00 Avatar answered Dec 24 '22 01:12

jfriend00