How do I get the path to the current script with Node.js?
In Node.js’s CommonJS module system, you can use the __filename
and __dirname
global variables:
__filename
gives the absolute path of the current executing file (including the file name).__dirname
gives the absolute path of the directory**** containing the current file.
For example:
console.log('Current file path:', __filename); console.log('Current directory path:', __dirname);
Example Output (depending on your system):
Current file path: /Users/yourname/projects/my-app/index.js
Current directory path: /Users/yourname/projects/my-app
Additional Tips
- Extracting File or Directory Names: If you need just the file name or parent directory name, you can use the Node.js
path
module:const path = require('path'); console.log('File name:', path.basename(__filename)); // e.g., "index.js" console.log('Directory name:', path.basename(__dirname)); // e.g., "my-app"
- Using ES Modules: If you’re using ECMAScript modules (
"type": "module"
inpackage.json
),__filename
and__dirname
are not defined by default. You can recreate them usingimport.meta.url
:import { fileURLToPath } from 'url'; import { dirname } from 'path'; const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename);
Recommended Resource
With these variables, you can reliably access file paths and directories relative to the current script in a Node.js environment.
CONTRIBUTOR
TechGrind