I would like to do something like this:
var jsonFileName = aDynamicallyGeneratedJsonFileName(),
defaultObject = {'my': 'default', 'json': 'object'};
var cachedOrRequiredObject = require(jsonFileName, defaultObject);
I would like for cachedOrRequiredObject
to be given defaultObject
if jsonFileName
doesn't exist, and I would like for the require cache to keep jsonFileName
as a key to defaultObject
even when jsonFileName
doesn't exist.
Of course this doesn't work -- in particular require errors when it can't find the file. I could do something like:
function myRequire (file, defaultObj) {
try {
return require(file);
catch () {
return defaultObj;
}
}
But every execution of require
is going to hit the file system to try to find file
when it doesn't exist. Is there a better way for me to do this short of duplicating require's functionality and maintaining my own cache?
You have to maintain your own cache for non-existent files, require
has no reason to do that. A very simple object cache is enough (and is what require() uses internally):
function requireWithDefault(path, default){
var module
if ((module = requireCache[path]) === undefined){
try {
module = require(path)
} catch(e) {
module = requireCache[path] = default
}
}
return module
}