Reputation: 55729
I prefer to import dependencies without lots of relative filesystem navigation like ../../../foo/bar
.
In the front-end I have traditionally used RequireJS to configure a default base path which enables "absolute" pathing e.g. myapp/foo/bar
.
How can I achieve this in Node.js?
Upvotes: 2
Views: 869
Reputation: 2241
Just to add to the other answer, you can put this few lines in your main file:
(function (module) {
let path = require('path')
let __require = module.constructor.prototype.require
let __cpath = __dirname
module.constructor.prototype.require = function (str) {
if (str.startsWith('package:')) {
let package = str.substr(8)
let p = path.resolve(__dirname, package)
return __require(p)
} else {
return __require(str)
}
}
})(module)
It extends your require
in such way:
package:
(i.e. package:src/foo/bar
) it translates it to require('/absolute/path/to/your/app/src/foo/bar')
,package:
then it behaves like a normal require
would.Upvotes: 1
Reputation: 24604
What you can do is use require.main.require
which would always be the module path of the starting file. See https://nodejs.org/api/modules.html#modules_accessing_the_main_module
This means, that when you run
const x = require.main.require('some/file/path/y')
It would require it based on the base path of your starting file (that was invoked , node app.js
meaning the app.js file).
Other options include using process.cwd()
to get the starting path of your app, but that would be depending on where you invoke your node process, not the location of the file. Meaning, node app.js
would be different than of you would start it one level up, node src/app.js
.
Upvotes: 1