How to get the current file path in Node

Published on

Accessing the current file path in Node can be handled in multiple ways.

The easiest way to get the current file path in NodeJS is to use the module variable __dirname. An example of how to use this is below:

console.log(__dirname); // Outputs a string of the current file path

There is also another variable that works very similar called __filename, but __filename will return the filename as well as the current directory.

Another method to access the current file path is using process.cwd() method. However, in order to use this method, you will first need to require the process module. An example of this can be found below:

const process = require('process');
console.log(process.cwd()); // Outputs a string of the current file path

If you are trying to get the current file path in Node to import a module, you should rather use the following syntax.

Say you have two files in your folder, main.js and another.js. To include an exported function from another.js in main.js you would write the following:

const someExportedFunction = require('./another');

./ is a relative path, and refers to the current working directory, and then we add the filename of where our exported function lives.