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?
2 Answers
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:
Create a repository for your module (github for public or bitbucket for private repositories)
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": { } }
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",
Run
npm install
- Profit

- 17,858
- 4
- 64
- 81
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.