What is the best way to pass common variables into separate modules in Node.js?

后端 未结 4 668
慢半拍i
慢半拍i 2020-12-07 08:00

I use separate router files as modules for main app and auth app. I can\'t get the best way to pass variables(db client) into routers. I don\'t want to hardcode it or pass i

4条回答
  •  情歌与酒
    2020-12-07 08:38

    You can save yourself all the boilerplate code of wiring up your modules if you use a dependency injection framework

    This answer lists a few of them. I also built a simpler DI framework here.

    EDIT: below is a copy form the answer in case that page changes


    require is the way of managing dependencies in Node.js and surely it is intuitive and effective, but it has also its limitations.

    My advice is to take a look at some of the Dependency Injection containers available today for Node.js to have an idea on what are their pros/cons. Some of them are:

    • Scatter
    • Electrolyte
    • Wire
    • Intravenous
    • Pongular

    Just to name a few.

    Now the real question is, what can you achieve with a Node.js DI container, compared to a simple require?

    Pros:

    • better testability: modules accepts their dependencies as input
    • Inversion of Control: decide how to wire your modules without touching the main code of your application.
    • a customizable algorithm for resolving modules: dependencies have "virtual" identifiers, usually they are not bound to a path on the filesystem.
    • Better extensibility: enabled by IoC and "virtual" identifiers.
    • Other fancy stuff possible:
      • Async initialization
      • Module lifecycle management
      • Extensibility of the DI container itself
      • Can easily implement higher level abstractions (e.g. AOP)

    Cons:

    • Different from the Node.js "experience": not using require definitely feels like you are deviating from the Node way of thinking.
    • The relationship between a dependency and its implementation is not always explicit. A dependency may be resolved at runtime and influenced by various parameters. The code becomes more difficult to understand and debug
    • Slower startup time
    • Maturity (at the moment): none of the current solutions is really popular at the moment, so not so many tutorials, no ecosystem, not battle tested.
    • Some DI containers will not play well with module bundlers like Browserify and Webpack.

提交回复
热议问题