Skip to content

Instantly share code, notes, and snippets.

@devinrhode2
Created July 15, 2012 07:01
Show Gist options
  • Save devinrhode2/3115640 to your computer and use it in GitHub Desktop.
Save devinrhode2/3115640 to your computer and use it in GitHub Desktop.
have require('file.js') fallback to trying require(./file.js')
/*
let's say you have some js file in your root. It's natural to expect this to work:
require('thing.js');
but it fails, reporting the module isn't available.
...but if it fails, why not check if it's at the root of the directory?
The below code overrides and wraps node's require function to do just that.
*/
var normalRequire = require;
var require = function newRequire(module) {
var returnValue;
try {
returnValue = normalRequire(module);
} catch (e) {
var message = e.message.toString();
//EcmaScript 6 .contains:
String.prototype.contains = function StringPrototypeContains(substring) {
return this.indexOf(substring) > -1;
};
if (message.contains('Cannot find module')) {
var path = './' + message.substring(message.indexOf("'") + 1, message.length - 1);
console.log('going to do require(\'' + path + '\');');
returnValue = require(path);
}
}
return returnValue;
};
@isaacs
Copy link

isaacs commented Jul 15, 2012

It's a lot easier to just say module.paths.push(__dirname). https://gist.github.com/3117649

Note: This should not be done. It's a design goal to make local requires obviously different from "outside the package" requires (either builtin modules or package deps.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment