In this article we'll see what are __dirname and __filename variables in Node.js and how to use them.
__dirname in Node.js
__dirname in Node.js is a convenience variable which stores the absolute path of the directory where the currently executing file (module) resides.
__dirname examples
Suppose project structure is as given below.
myapp
| app.js
| package-lock.json
| package.json
+---bin
+---controllers
| product.js
+---node_modules
+---public
| +---docs
| +---images
| +---javascripts
| +---stylesheets
+---routes
| index.js
| users.js
\---views
error.ejs
index.ejs
In the app.js if we have the following line of code
console.log('Directory path- ' + __dirname);
then on running the app.js file output is
Directory path- D:\NETJS\NodeJS\nodews\myapp
Which is the absolute path of the directory where app.js file resides.
You can use __dirname in conjunction with path.join() to create paths relative to current file path. For example, if you need to read a file named hello.txt which is inside /public/docs as per the given project structure then you can construct the path using __dirname as given below-
const filePath = path.join(__dirname, "/public/docs/", "hello.txt");
console.log(filePath);
fs.readFile(filePath,'utf8', (err, data) => {
if(err){
console.log('Error while reading file');
}else{
console.log(data);
}
});
Output for the filePath is-
D:\NETJS\NodeJS\nodews\myapp\public\docs\hello.txt
__filename in Node.js
__filename in Node.js is a convenience variable which stores the current module file's absolute path.
__filename examples
If we use the same project structure as already mentioned above then having the following lines in app.js
console.log('File Name- ' + __filename);
console.log('Directory path- ' + __dirname);
Gives us the following output
File Name- D:\NETJS\NodeJS\nodews\myapp\app.js Directory path- D:\NETJS\NodeJS\nodews\myapp
If you want just the file name not the full path then wrap __filename in path.basename() method.
console.log('File Name- ' + path.basename(__filename));
Output
File Name- app.js
That's all for this topic __dirname and __filename in Node.js. If you have any doubt or any suggestions to make please drop a comment. Thanks!
Related Topics
You may also like-
No comments:
Post a Comment