Node’s require doesn’t always return the same value

Node’s require doesn’t always return the same value

This is just a curious edge case in node.js I came across while looking at creating the module system for microvium.

The node.js documentation says:

… every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.

But this doesn’t seem entirely true. In the following code, a module imports itself twice, getting a different object each time:

// script.js 

const a = {};
const b = {};

module.exports = a;
const a2 = require('./script');
module.exports = b;
const a3 = require('./script');
console.log(a2 === a3); // false

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.