Is it a bad practice to use `require` inside a constructor in NodeJS?bad practice to strip out all require statements into a separate file?is it bad practice to require php files rather than link to js and css?Repeated requirements that expose a function/constructor in NodejsNodejs - implementing modules with constructors or object literalsReuse code inside if statement. (Is function inside function bad practice?)How to use require inside global and local functionGet constructor parameter from JSON, inside the constructor?Node: requiring module inside function?Is it “bad practice” to require() within a gulp task?typescript replaceent for require inside a function in nodejs

If p-value is exactly 1 (1.0000000), what are the confidence interval limits?

Confusion in understanding control system?

Is mathematics truth?

When making yogurt, why doesn't bad bacteria grow as well?

Why do old games use flashing as means of showing damage?

Short story with a first person narrator in a future where racial conflict had exploded into an all out war

What drugs were used in England during the High Middle Ages?

How to deal with an incompetent collaborator

Count rook moves 1D

Case Studies and Real Problems for Teaching Optimization and Modelling

Strange formulas that gave rise to Koszul duality

Japanese equivalent for "get to do something"?

Why would a Intel 8080 chip be destroyed if +12 V is connected before -5 V?

Does POSIX guarantee the paths to any standard utilities?

Why do we need explainable AI?

Did Alan Turing's student Robin Gandy assert that Charles Babbage had no notion of a universal computing machine?

How do you manage to study and have a balance in your life at the same time?

Is it rude to ask my opponent to resign an online game when they have a lost endgame?

slowest crash on the Moon?

What is this red bug infesting some trees in southern Germany?

Is torque as fundamental a concept as force?

Deleting polylines based on features from an attribute table

Can I take a soft suitcase on Qatar Airways?

Do index funds really have double-digit percents annual return rates?



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


bad practice to strip out all require statements into a separate file?is it bad practice to require php files rather than link to js and css?Repeated requirements that expose a function/constructor in NodejsNodejs - implementing modules with constructors or object literalsReuse code inside if statement. (Is function inside function bad practice?)How to use require inside global and local functionGet constructor parameter from JSON, inside the constructor?Node: requiring module inside function?Is it “bad practice” to require() within a gulp task?typescript replaceent for require inside a function in nodejs






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








2















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?










share|improve this question





















  • 1





    I would require it once and use the variable once I have the parameter

    – Luca Kiebel
    Jun 5 '18 at 15:03

















2















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?










share|improve this question





















  • 1





    I would require it once and use the variable once I have the parameter

    – Luca Kiebel
    Jun 5 '18 at 15:03













2












2








2








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?










share|improve this question
















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?







javascript json node.js require






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jun 5 '18 at 15:09









Bjoern Rennhak

5,3161 gold badge11 silver badges20 bronze badges




5,3161 gold badge11 silver badges20 bronze badges










asked Jun 5 '18 at 14:58









Nick GarlisNick Garlis

627 bronze badges




627 bronze badges










  • 1





    I would require it once and use the variable once I have the parameter

    – Luca Kiebel
    Jun 5 '18 at 15:03












  • 1





    I would require it once and use the variable once I have the parameter

    – Luca Kiebel
    Jun 5 '18 at 15:03







1




1





I would require it once and use the variable once I have the parameter

– Luca Kiebel
Jun 5 '18 at 15:03





I would require it once and use the variable once I have the parameter

– Luca Kiebel
Jun 5 '18 at 15:03












2 Answers
2






active

oldest

votes


















5
















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.






share|improve this answer


































    1

















    Is this a bad practice?




    Not really, require has a cache so it doesn't matter a lot.




    I've heard people say that you should always use require in the beginning of your code.




    Yes, that's a good practice so that one can easily spot the dependencies.




    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 of the constructor?




    Yes, I would do that. I'd only put require inside the constructor if it was a dynamic dependency, like const wordlist = require(./config/lang/$lang.json).






    share|improve this answer



























      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f50703187%2fis-it-a-bad-practice-to-use-require-inside-a-constructor-in-nodejs%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      5
















      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.






      share|improve this answer































        5
















        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.






        share|improve this answer





























          5














          5










          5









          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.






          share|improve this answer















          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.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 28 at 2:50

























          answered Jun 5 '18 at 15:05









          Marcos CasagrandeMarcos Casagrande

          16k3 gold badges31 silver badges47 bronze badges




          16k3 gold badges31 silver badges47 bronze badges


























              1

















              Is this a bad practice?




              Not really, require has a cache so it doesn't matter a lot.




              I've heard people say that you should always use require in the beginning of your code.




              Yes, that's a good practice so that one can easily spot the dependencies.




              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 of the constructor?




              Yes, I would do that. I'd only put require inside the constructor if it was a dynamic dependency, like const wordlist = require(./config/lang/$lang.json).






              share|improve this answer





























                1

















                Is this a bad practice?




                Not really, require has a cache so it doesn't matter a lot.




                I've heard people say that you should always use require in the beginning of your code.




                Yes, that's a good practice so that one can easily spot the dependencies.




                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 of the constructor?




                Yes, I would do that. I'd only put require inside the constructor if it was a dynamic dependency, like const wordlist = require(./config/lang/$lang.json).






                share|improve this answer



























                  1














                  1










                  1










                  Is this a bad practice?




                  Not really, require has a cache so it doesn't matter a lot.




                  I've heard people say that you should always use require in the beginning of your code.




                  Yes, that's a good practice so that one can easily spot the dependencies.




                  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 of the constructor?




                  Yes, I would do that. I'd only put require inside the constructor if it was a dynamic dependency, like const wordlist = require(./config/lang/$lang.json).






                  share|improve this answer














                  Is this a bad practice?




                  Not really, require has a cache so it doesn't matter a lot.




                  I've heard people say that you should always use require in the beginning of your code.




                  Yes, that's a good practice so that one can easily spot the dependencies.




                  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 of the constructor?




                  Yes, I would do that. I'd only put require inside the constructor if it was a dynamic dependency, like const wordlist = require(./config/lang/$lang.json).







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jun 5 '18 at 15:10









                  BergiBergi

                  403k68 gold badges639 silver badges964 bronze badges




                  403k68 gold badges639 silver badges964 bronze badges






























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f50703187%2fis-it-a-bad-practice-to-use-require-inside-a-constructor-in-nodejs%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                      용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

                      155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해