The path module and __dirname


1 | Why use the path module?


The path module provides useful methods for working with files and directory paths. Also, the path module makes sure that the paths of files and directories in our Node.js environment are Operating-System-agnostic.


In any Operating System, a path points to a file system location by following the directory tree hierarchy expressed in a string of characters. The components of the path, i.e. the different strings, are separated by a delimiting character and represent a directory. The delimiting character can be different from one OS to the other. For instance, most Unix-like Operating Systems, such as macOS and most Linux distributions, use the POSIX syntax for their path. The delimiting character is a slash. However, Windows uses a backslash as a delimiter. The path module enables a universal way to refer to path of files and directories, regardless on which OS the Node.js environment runs in.


The path module can be accessed like this:


const path = require('path');

In the previous code, we require the path module and assign all of its properties to the variable path.


2 | __dirname

The __dirname variable is a Node.js environment variable that returns the absolute path of the directory containing the current file. It is the most secure way to obtain the absolute path of the directory in which a file is located. Even though it is similar to using the method path.dirname(), this last method is quite useless, since we must provide the path of the file as an argument. This defeats the purpose of obtaining the path of the current directory when we do not know it or do not want to rebuild it.


3 | path.join()


The method path.join() method joins all given path segments together using the platform-specific separator as a delimiter. This method is quite useful to change directories to refer other files, as we can use the .. to go up a directory or . to refer to a current directory.


Example: We say that we are in the test.js file


// test.js
const path = require('path');
const ENIGMA_FILE = path.join(__dirname, .., assets, 'enigma.txt);

We require the path module and assign all of its properties to the variable path. Then, we use the method path.join(), that lets us specify the path of our enigma.txt file. This enigma.txt file happens to be in a sibling directory of the directory of our current test.js file called assets.


4 | Other methods


There are other methods defined in the Node.js path module, but we think the previous information is quite enough for most common to get started with referring files and directories in Node.js. You can explore these methods in the Node.js documentation: https://nodejs.org/docs/latest/api/path.html.


Author: Dimitri Alamkan
Initial publication date:
Last updated: