Node.js caching of required scripts

When I started exploring node.js I was wondering how the require() thing worked and how it would cache the scripts I required.

Would it return a new instance every time, basically functioning as a factory? Or would it return the same instance over and over?

So I did some reading up and found out that node.js caches it and returns the cached object/instance. Good, but then I read that it uses the filename for cache key, but it wasn't clear if the absolute file name is used as cache key or the relative file name.

So I did a test.

./index.js:

1
2
3
4
5
var test = require('./modules/test/test2.js');
console.log('expect world', test.hello);
test.hello = "dirt";
require('./modules/testbed.js');
console.log('expect universe', test.hello);

./modules/test/test2.js

1
2
3
module.exports = {
    hello: 'world'
}


./modules/testbed.js

1
2
3
var test2 = require('./test/test2.js');
console.log('expect dirt', test.hello);
test2.hello = "universe";

And then the output becomes

index.js:2   expect world world
testbed.js:2 expect dirt dirt
index.js:5   expect universe universe

Giving me confidence that it doesn't matter from which file or directory you require the module, as long as the filename is the same.

The only caveat is that if you use a case insensitive file system, things will break down if you're not consequent in your filename strings.

For example: if you change testbed.js to contain this:

1
2
3
var test2 = require('./test/Test2.js');// Note the uppercase T
console.log('expect dirt', test2.hello);
test2.hello = "universe";

The output will become:

index.js:2   expect world world
testbed.js:2 expect dirt world
index.js:5   expect universe dirt

because test.js and Test.js are different strings. So make sure to either always use consistent case for filenames.

Comments

Popular Posts