Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Require , how to do a fallback when module does not exist

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

like image 657
keerti Avatar asked Jun 26 '26 09:06

keerti


2 Answers

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');
  }
}
like image 186
Duncan Walker Avatar answered Jun 28 '26 22:06

Duncan Walker


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.

like image 28
Jared Goguen Avatar answered Jun 28 '26 23:06

Jared Goguen