Skip to content Skip to sidebar Skip to footer

Nodejs Require - Module Name Case Sensitive Issue

recently i found out a strange problem regarding the node.js require mechanism you might think, due to windows file system it doesn't matter if required modules are case sensitive

Solution 1:

First of all, never make assumptions about the filesystem you are using. Always expect it to be case sensitive, in case you run it in a different environment.

Now to your problem:

When you require a module in node, node will cache the import exactly to prevent the case where you want to export a singleton and not have it initialized twice. While the filesystem lookup will return the same exact file because it's case insensitive, require's cache still treats the two cases as different modules. That's because it has to assume that it runs in a case sensitive environment, so there could actually be two different modules behind that.

That's why it initializes your singleton twice. It actually treats them as two different modules.

You were asking if there's any way to prevent it. There is a very easy but horrible way to do it. You can patch global.require to lowercase your imports:

var patchRequire = function () {
    var oldRequire = global.require;
    global.require = function (moduleName) {
        return oldRequire.call(global, moduleName.toLowerCase());
    };
};

patchRequire();
require('Foo-Bar'); // Will require 'foo-bar' instead

But please don't do that. Better make sure to keep your imports consistent and use all lower case names separated by dashes.

Post a Comment for "Nodejs Require - Module Name Case Sensitive Issue"