1292

How would I get the path to the script in Node.js?

I know there's process.cwd, but that only refers to the directory where the script was called, not of the script itself. For instance, say I'm in /home/kyle/ and I run the following command:

node /home/kyle/some/dir/file.js

If I call process.cwd(), I get /home/kyle/, not /home/kyle/some/dir/. Is there a way to get that directory?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Kyle Slattery
  • 33,318
  • 9
  • 32
  • 36
  • 6
    http://nodejs.org/docs/latest/api/globals.html the documentation link of the accepted answer. – allenhwkim Apr 12 '13 at 15:41
  • This was helpful for me: `const sqlFolder = path.join(path.join(process.cwd(), 'db'), 'queries');` https://vercel.com/guides/loading-static-file-nextjs-api-route – Ryan Nov 22 '22 at 17:28

15 Answers15

1713

I found it after looking through the documentation again. What I was looking for were the __filename and __dirname module-level variables.

  • __filename is the file name of the current module. This is the resolved absolute path of the current module file. (ex:/home/kyle/some/dir/file.js)
  • __dirname is the directory name of the current module. (ex:/home/kyle/some/dir)
doom
  • 3,276
  • 4
  • 30
  • 41
Kyle Slattery
  • 33,318
  • 9
  • 32
  • 36
311

So basically you can do this:

fs.readFile(path.resolve(__dirname, 'settings.json'), 'UTF-8', callback);

Use resolve() instead of concatenating with '/' or '\' else you will run into cross-platform issues.

Note: __dirname is the local path of the module or included script. If you are writing a plugin which needs to know the path of the main script it is:

require.main.filename

or, to just get the folder name:

require('path').dirname(require.main.filename)
Marc
  • 13,011
  • 11
  • 78
  • 98
  • 17
    If your goal is just to parse and interact with the json file, you can often do this more easily via `var settings = require('./settings.json')`. Of course, it's synchronous fs IO, so don't do it at run-time, but at startup time it's fine, and once it's loaded, it'll be cached. – isaacs May 09 '12 at 18:26
  • 3
    @Marc Thanks! For a while now I was hacking my way around the fact that __dirname is local to each module. I have a nested structure in my library and need to know in several places the root of my app. Glad I know how to do this now :D – Thijs Koerselman Feb 28 '13 at 14:34
  • Node V8: path.dirname(process.mainModule.filename) – wayofthefuture Aug 26 '17 at 11:47
  • 3
    This [no longer works with ES modules](https://stackoverflow.com/questions/3133243/how-do-i-get-the-path-to-the-current-script-with-node-js/50053801#50053801). – Dan Dascalescu Apr 25 '19 at 00:38
  • @RayFoss be careful in general with string operations on directory separators, there can be surprises in both parsing and concatenation; I think most operating systems tolerate excessive slashes (e.g., `//////home//////yourname///////` is a valid path), but irresponsible use of concatenation can make something that really is unreadable in some cases if you make assumptions about whether a path will have an ending slash or not, or if a slash accidentally gets appended to a file name like /home/yourname/yourfile.png/ – jrh May 16 '19 at 18:40
  • Isn't `path.join` a bit more suitable than `path.resolve`? – Skorunka František Jan 23 '21 at 09:14
  • @RayFoss Symbian and Solaris are a higher priority for you than Windows? – forresthopkinsa Aug 17 '21 at 22:34
  • @forrestthopkinsa basically I don't support any file system that allows forward slashes in file names. Windows exists, but so does WSL, Docker and BusyBox... I can think of no reason to consider DOS idiosyncrasies unless it's for the purpose of writing a POSIX layer, migrating a legacy codebase or making a Filesystem storage adapter; Even then, the cloud is everything and the cloud is 99.9+% Linux. – Ray Foss Aug 26 '21 at 07:56
170

Use __dirname!!

__dirname

The directory name of the current module. This the same as the path.dirname() of the __filename.

Example: running node example.js from /Users/mjr

console.log(__dirname);
// Prints: /Users/mjr
console.log(path.dirname(__filename));
// Prints: /Users/mjr

https://nodejs.org/api/modules.html#modules_dirname

For ESModules you would want to use: import.meta.url

Playdome.io
  • 3,137
  • 2
  • 17
  • 34
  • 1
    This survives symlinks too. So if you create a bin and need to find a file, eg path.join(__dirname, "../example.json"); it will still work when your binary is linked in node_modules/.bin – Jason Apr 17 '18 at 17:12
  • 6
    Not only was this answer given years earlier, it also [no longer works with ES modules](https://stackoverflow.com/questions/3133243/how-do-i-get-the-path-to-the-current-script-with-node-js/50053801#50053801). – Dan Dascalescu Apr 25 '19 at 00:39
167

Node.js 10 supports ECMAScript modules, where __dirname and __filename are no longer available.

Then to get the path to the current ES module one has to use:

import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);

And for the directory containing the current module:

import { dirname } from 'path';
import { fileURLToPath } from 'url';

const __dirname = dirname(fileURLToPath(import.meta.url));
GOTO 0
  • 42,323
  • 22
  • 125
  • 158
  • How would I know if I'm writing an ES module or not? Is it just a matter of which Node version I'm running, or if I'm using import/export keywords? – Ed Brannin Apr 18 '19 at 19:42
  • 3
    ES modules available only with `--experimental-modules` flag. – Nickensoul May 07 '19 at 16:01
  • 5
    --experimental-modules is only required if you are running node version is < 13.2. just name the file .mjs rather than .js – Brent Apr 12 '20 at 19:56
  • 2
    Yes this works. @Nickensoul or in package.json "type": "module", – Johan Hoeksma May 12 '21 at 13:34
  • Warning, if you are using a bundler, this is the path to the source file. If you build and deploy to a different folder, it is still the path to the original source file. – Dirigible Dec 27 '22 at 17:31
  • If someone has troubles getting the __dirname you can use: `const __dirname = dirname(fileURLToPath(import.meta.url));` – Tajs May 25 '23 at 16:42
154

This command returns the current directory:

var currentPath = process.cwd();

For example, to use the path to read the file:

var fs = require('fs');
fs.readFile(process.cwd() + "\\text.txt", function(err, data)
{
    if(err)
        console.log(err)
    else
        console.log(data.toString());
});
dYale
  • 1,541
  • 1
  • 16
  • 19
Masoud Siahkali
  • 5,100
  • 1
  • 29
  • 18
  • For those who didn't understand **Asynchronous** and **Synchronous**, see this link... http://stackoverflow.com/a/748235/5287072 – DarckBlezzer Feb 03 '17 at 17:33
  • 33
    this is exactly what the OP doesn't want... the request is for the path of the executable script! – caesarsol Mar 29 '18 at 09:10
  • 10
    Current directory is a very different thing. If you run something like `cd /foo; node bar/test.js`, current directory would be `/foo`, but the script is located in `/foo/bar/test.js`. – rjmunro Jul 05 '18 at 11:20
  • 2
    It's not a good answer. It's mess a logic beacauese this can be much shorter path than you expect. – kris_IV Apr 09 '19 at 11:31
  • 2
    Why would you ever do this; if the file were relative to the current directory you could just read `text.txt` and it would work, you don't need to construct the absolute path – Michael Mrozek Oct 03 '19 at 03:40
56

When it comes to the main script it's as simple as:

process.argv[1]

From the Node.js documentation:

process.argv

An array containing the command line arguments. The first element will be 'node', the second element will be the path to the JavaScript file. The next elements will be any additional command line arguments.

If you need to know the path of a module file then use __filename.

Community
  • 1
  • 1
Lukasz Wiktor
  • 19,644
  • 5
  • 69
  • 82
  • 3
    @Tamlyn Maybe because `process.argv[1]` applies only to the main script while `__filename` points to the module file being executed. I update my answer to emphasize the difference. Still, I see nothing wrong in using `process.argv[1]`. Depends on one's requirements. – Lukasz Wiktor Jan 16 '16 at 06:40
  • 15
    If main script was launched with a node process manager like pm2 process.argv[1] will point to the executable of the process manager /usr/local/lib/node_modules/pm2/lib/ProcessContainerFork.js – user3002996 Mar 01 '17 at 11:28
27
var settings = 
    JSON.parse(
        require('fs').readFileSync(
            require('path').resolve(
                __dirname, 
                'settings.json'),
            'utf8'));
Community
  • 1
  • 1
foobar
  • 287
  • 3
  • 2
  • 7
    Just a note, as of node 0.5 you can just require a JSON file. Of course that wouldn't answer the question. – Kevin Cox Apr 09 '13 at 21:18
  • 3
    `__dirname` [no longer works with ES modules](https://stackoverflow.com/questions/3133243/how-do-i-get-the-path-to-the-current-script-with-node-js/50053801#50053801). – Dan Dascalescu Apr 25 '19 at 00:40
21

Every Node.js program has some global variables in its environment, which represents some information about your process and one of it is __dirname.

Omar Ali
  • 8,467
  • 4
  • 33
  • 58
Hazarapet Tunanyan
  • 2,809
  • 26
  • 30
  • 2
    Not only was this answer given years earlier, `__dirname` [no longer works with ES modules](https://stackoverflow.com/questions/3133243/how-do-i-get-the-path-to-the-current-script-with-node-js/50053801#50053801). – Dan Dascalescu Apr 25 '19 at 00:40
  • It's about NodeJs 10, but this answer was published in 2016. – Hazarapet Tunanyan May 03 '19 at 07:59
17

I know this is pretty old, and the original question I was responding to is marked as duplicate and directed here, but I ran into an issue trying to get jasmine-reporters to work and didn't like the idea that I had to downgrade in order for it to work. I found out that jasmine-reporters wasn't resolving the savePath correctly and was actually putting the reports folder output in jasmine-reporters directory instead of the root directory of where I ran gulp. In order to make this work correctly I ended up using process.env.INIT_CWD to get the initial Current Working Directory which should be the directory where you ran gulp. Hope this helps someone.

var reporters = require('jasmine-reporters');
var junitReporter = new reporters.JUnitXmlReporter({
  savePath: process.env.INIT_CWD + '/report/e2e/',
  consolidateAll: true,
  captureStdout: true
 });
Mike
  • 14,010
  • 29
  • 101
  • 161
Dana Harris
  • 387
  • 3
  • 6
14

Use the basename method of the path module:

var path = require('path');
var filename = path.basename(__filename);
console.log(filename);

Here is the documentation the above example is taken from.

As Dan pointed out, Node is working on ECMAScript modules with the "--experimental-modules" flag. Node 12 still supports __dirname and __filename as above.


If you are using the --experimental-modules flag, there is an alternative approach.

The alternative is to get the path to the current ES module:

import { fileURLToPath } from 'url';
const __filename = fileURLToPath(new URL(import.meta.url));

And for the directory containing the current module:

import { fileURLToPath } from 'url';
import path from 'path';

const __dirname = path.dirname(fileURLToPath(new URL(import.meta.url)));
PJ Eby
  • 8,760
  • 5
  • 23
  • 19
Michael Cole
  • 15,473
  • 7
  • 79
  • 96
12

NodeJS exposes a global variable called __dirname.

__dirname returns the full path of the folder where the JavaScript file resides.

So, as an example, for Windows, if we create a script file with the following line:

console.log(__dirname);

And run that script using:

node ./innerFolder1/innerFolder2/innerFolder3/index.js

The output will be: C:\Users...<project-directory>\innerFolder1\innerFolder2\innerFolder3

Idan Krupnik
  • 443
  • 1
  • 6
  • 8
8

You can use process.env.PWD to get the current app folder path.

AbiSivam
  • 419
  • 1
  • 6
  • 17
  • 7
    OP asks for the requested "path to the script". PWD, which stands for something like Process Working Directory, is not that. Also, the "current app" phrasing is misleading. – dmcontador Sep 08 '17 at 06:48
8

If you are using pkg to package your app, you'll find useful this expression:

appDirectory = require('path').dirname(process.pkg ? process.execPath : (require.main ? require.main.filename : process.argv[0]));
  • process.pkg tells if the app has been packaged by pkg.

  • process.execPath holds the full path of the executable, which is /usr/bin/node or similar for direct invocations of scripts (node test.js), or the packaged app.

  • require.main.filename holds the full path of the main script, but it's empty when Node runs in interactive mode.

  • __dirname holds the full path of the current script, so I'm not using it (although it may be what OP asks; then better use appDirectory = process.pkg ? require('path').dirname(process.execPath) : (__dirname || require('path').dirname(process.argv[0])); noting that in interactive mode __dirname is empty.

  • For interactive mode, use either process.argv[0] to get the path to the Node executable or process.cwd() to get the current directory.

dmcontador
  • 660
  • 1
  • 8
  • 18
1

index.js within any folder containing modules to export

const entries = {};
for (const aFile of require('fs').readdirSync(__dirname, { withFileTypes: true }).filter(ent => ent.isFile() && ent.name !== 'index.js')) {
  const [ name, suffix ] = aFile.name.split('.');
  entries[name] = require(`./${aFile.name}`);
}

module.exports = entries;

This will find all files in the root of the current directory, require and export every file present with the same export name as the filename stem.

Andy Lorenz
  • 2,905
  • 1
  • 29
  • 29
-4

If you want something more like $0 in a shell script, try this:

var path = require('path');

var command = getCurrentScriptPath();

console.log(`Usage: ${command} <foo> <bar>`);

function getCurrentScriptPath () {
    // Relative path from current working directory to the location of this script
    var pathToScript = path.relative(process.cwd(), __filename);

    // Check if current working dir is the same as the script
    if (process.cwd() === __dirname) {
        // E.g. "./foobar.js"
        return '.' + path.sep + pathToScript;
    } else {
        // E.g. "foo/bar/baz.js"
        return pathToScript;
    }
}
dmayo3
  • 73
  • 5
  • `__dirname` and `__filename` are [no longer available with ES modules](https://stackoverflow.com/questions/3133243/how-do-i-get-the-path-to-the-current-script-with-node-js/50053801#50053801). – Dan Dascalescu Apr 25 '19 at 00:41