Thursday, June 13, 2024

__dirname and __filename in Node.js

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.

|   app.js
|   package-lock.json
|   package.json  
|       product.js     
|   +---docs      
|   +---images
|   +---javascripts
|   +---stylesheets           
|       index.js
|       users.js    

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");
fs.readFile(filePath,'utf8', (err, data) => {
    console.log('Error while reading file');

Output for the filePath is-

__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));


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

  1. Introduction to Node.js
  2. Difference Between __dirname and process.cwd() in Node.js
  3. Node.js REPL
  4. Node.js Event Driven Architecture
  5. NodeJS Blocking Non-blocking Code

You may also like-

  1. Appending a File in Node.js
  2. How to Pass Command Line Arguments in Eclipse
  3. String in Java Tutorial
  4. Angular Custom Property Binding Using @Input Decorator
  5. Spring MVC Dropdown Example Using Select, Option And Options Tag

No comments:

Post a Comment