Search code examples
javascriptjsonnode.jsrequire

Is it a bad practice to use `require` inside a constructor in NodeJS?


I am building a node app where a certain wordlist is required. The wordlist is in a JSON file that looks something like this:

 { 
   "en":["foo", "bar"],
   "gr": ["foo", "bar"]
 }

Each key inside of the JSON file represents a different language.

The user has to pick a language when they create their object. So I am thinking of importing the JSON file inside of the constructor like this:

const list = require('./config/lang.json')[lang]

Where lang is a parameter passed to the constructor.

Is this bad practice?

I've heard people say that you should always use require in the beginning of your code. Should I just require the whole thing in the beginning of my code const list = require('./config/lang.json') and then simply extract only the required language const wordlist = list[lang]inside the constructor?


Solution

  • Even though the code works the same, and require calls are cached. In your case there is no need for that extra function call on every new instance, so it will be faster (not that it matters in this case) to do the following:

    const langs = require('./config/lang.json');
    
    class MyClass {
        constructor(lang) {
            const list = langs[lang];
        }
    }
    

    Another thing to notice, is that require is synchronous, so if your JSON is specially large, the first time you instanciate MyClass the event loop will be blocked. Using it at the very beginning it will probably have loaded before the server (or whatever you're doing) has started, so there would be no issue in the require taking some time.

    So, yes, in my opinion, require calls should be at the top, unless you know what you're doing, or you're loading a dynamic dependency.