Skip to content

Instantly share code, notes, and snippets.

@hypesystem
Last active August 29, 2015 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hypesystem/9e6c7d5589e6bb3d0178 to your computer and use it in GitHub Desktop.
Save hypesystem/9e6c7d5589e6bb3d0178 to your computer and use it in GitHub Desktop.
module.parent refers to the first requirer only!

Module.parent is useless

module.parent in a node app refers to the parent module of the current module. This is useful for getting paths (for example) relative to the parent, for example used internally in fileGetter:

// Should get localPath in ./, not localPath in ./lib/some-folder
var fileGetter = require("./lib/some-folder/file-getter.js");
var text = fileGetter("./localPath.dat");

The problem is that this usecase is effectively completely useless: the file getter will get the path (using path.dirname(module.parent.filename)) relative to the first module that requires file getter. If the file getter is used several places in the application, the first require determines the path. As a result, it is completely and utterly useless.

Result

$ node example.js
User 1 <path>\user1.js
User 2 <path>\user1.js
Notice that these are identical (==user1.js). The guessing fails for user2.js because it was required second.
var user1 = require("./user1.js");
var user2 = require("./user2.js");
var fn1 = user1.guessMyFilename();
var fn2 = user2.guessMyFilename();
console.log("User 1", fn1);
console.log("User 2", fn2);
console.log("Notice that these are identical (==user1.js). The guessing fails for user2.js because it was required second.");
module.exports = function() {
return module.parent.filename;
};
var filenameGuesser = require("./filename-guesser.js");
module.exports = {
guessMyFilename: function() {
return filenameGuesser();
}
};
var filenameGuesser = require("./filename-guesser.js");
module.exports = {
guessMyFilename: function() {
return filenameGuesser();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment