I have an application where I need to require a file that may or may not be available. If the file is not available, I need to check for another file. and the third option will be default. So far I have this
const file = require('./locales/${test1}') || require('./locales/${test2}') || require('./locales/default')
But it gives me error saying cannot find module. How do I do it optimally?
I did try https://www.npmjs.com/package/node-require-fallback but it does not seem to work in spite of my node version being OK
const messages = require('./locales/${test1}') works well but
const messages = requireIfExists('./locales/${test1}', './locales/${test2}') FAILS
In a vanilla node app, you can use a try-catch block:
var module;
try {
module = require(`./locales/${test1}`);
} catch(error) {
// Do something as a fallback. For example:
module = require('./locales/default');
}
}
Using try/except, you can implement a function that replicates requireIfExists on your own.
function requireIfExists(...modules) {
for (let module of modules) {
try {
return require(module);
} catch (error) {
// pass and try next file
}
}
throw('None of the provided modules exist.')
}
Also, make sure you are using the ` character instead of quotes when using template strings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With