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 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
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./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
Share Improve this question edited Jul 2, 2018 at 16:27 Jared Goguen 9,0182 gold badges21 silver badges39 bronze badges asked Jan 2, 2018 at 17:33 keertikeerti 2556 silver badges20 bronze badges 1-
Are you using the ` character in your template strings instead of single quotes? The source of the module is on github and it pretty simple, so I'd expect something is wrong with the way you are using
requireIfExists
– Jared Goguen Commented Jul 2, 2018 at 16:25
2 Answers
Reset to default 6In 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.