In a Node.js module I would like to open a file--i.e, with fs.readFile()
--that is contained in the same directory as my module. By which I mean it is in the same directory as the ./node_modules/<module_name>/index.js
file.
It looks like all relative path operations which are performed by the fs
module take place relative to the directory in which Node.js is started. As such, I think I need to know how to get the path of the current Node.js module which is executing.
Thanks.
We can get the path of the present script in node. js by using __dirname and __filename module scope variables. __dirname: It returns the directory name of the current module in which the current script is located. __filename: It returns the file name of the current module.
Node. js provides you with the path module that allows you to interact with file paths easily. The path module has many useful properties and methods to access and manipulate paths in the file system. The path is a core module in Node.
Node will look for your modules in special folders named node_modules . A node_modules folder can be on the same level as the current file, or higher up in the directory chain. Node will walk up the directory chain, looking through each node_modules until it finds the module you tried to load.
As david van brink mentioned in the comments, the correct solution is to use __dirname
. This global variable will return the path of the currently executing script (i.e. you might need to use ../
to reach the root of your module).
For example:
var path = require("path"); require(path.join(__dirname, '/models'));
Just to save someone from a headache.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With