2

I am looking for a good nodejs dependancy injection module, I implemented a special logger module and I want to be able getting the instance of the logger no matter where my position in the folder hierarchy. I can't simply use requirejs because with requirejs I need the full relative path to the module. Is there a standard suitable solution?

Shlomi Hassan
  • 177
  • 1
  • 11

2 Answers2

1

I would still suggest you to use the require() way, since it's native for node.js

Though, if you don't want to bother yourself with the relative paths - your module should reside in the node_modules folder inside your project. To achieve this, you could install it via npm.

But before installing it, you should publish it somewhere, of course.

I would recommend you to take this as a practice:

  1. Create a repository for your module (github for public or bitbucket for private repositories)

  2. Create a package.json file for your module. Here is an example:

    {
        "name": "your-module",
        "private": true,
        "repository": {
            "type": "git",
            "url": "git@bitbucket.org:username/your-module.git"
        },
        "main": "index.js",
        "version": "1.0.0",
        "dependencies": {
        }
    }
    
  3. Add a dependency to this module into your main package.json like this

    "your-module": "git+ssh://git@bitbucket.org:username/your-module.git#1.1.0",
    
  4. Run npm install

  5. Profit
Vitalii Zurian
  • 17,858
  • 4
  • 64
  • 81
1

I would also recommend following Node.js conventions.

It is possible to store the location of the current file, for instance in the main file (supposedly at the root of your project) using dirname or filename. Then, storing it in the global variable will make it accessible from everywhere in your app. I find it quite dirty though.

Community
  • 1
  • 1
nha
  • 17,623
  • 13
  • 87
  • 133