How do I get the path to the current script with Node.js? - node.js

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?

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)

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)

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

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());
});

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

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.

var settings =
JSON.parse(
require('fs').readFileSync(
require('path').resolve(
__dirname,
'settings.json'),
'utf8'));

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

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

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

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

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

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.

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.

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;
}
}

Related

Take relative file path as CLI input in a Node program

In a CLI app, I need to take in a relative path to a file, and pass an absolute path to fs.readFile. How can I accept the relative path as input but convert it to an absolute path, even if the Node script is being run from a different directory than it is in?
You can use path.resolve with process.cwd() and the input file.
When you have a path relative to the JS file you are running, you usually use path.resolve with __dirname. However, in the case where the user supplies a path as a CLI argument, they may be running the JS file from a different directory. To get the directory they are running the script from, you can use process.cwd() (Current Working Directory).
$ node some-folder/index.js ./myFile.txt
const { resolve } = require("node:path")
const { argv, cwd } = require("node:process")
// or with ESM
import { resolve } from "node:path"
import { argv, cwd } from "node:process"
const relativePath = argv[2] // input file
const absolutePath = resolve(cwd(), relativePath)
// absolutePath looks like /.../myFile.txt, but if we
// used __dirname instead of cwd(), it would be
// /.../some-folder/myFile.txt, relative to the JS file
// instead of where the file was ran from
// now you can use absolutePath with fs.readFile or etc

How to create file on the project that installed your package? [duplicate]

Is there a different way, other than process.cwd(), to get the pathname of the current project's root-directory. Does Node implement something like ruby's property, Rails.root,. I'm looking for something that is constant, and reliable.
There are many ways to approach this, each with their own pros and cons:
require.main.filename
From http://nodejs.org/api/modules.html:
When a file is run directly from Node, require.main is set to its module. That means that you can determine whether a file has been run directly by testing require.main === module
Because module provides a filename property (normally equivalent to __filename), the entry point of the current application can be obtained by checking require.main.filename.
So if you want the base directory for your app, you can do:
const { dirname } = require('path');
const appDir = dirname(require.main.filename);
Pros & Cons
This will work great most of the time, but if you're running your app with a launcher like pm2 or running mocha tests, this method will fail. This also won't work when using Node.js ES modules, where require.main is not available.
module.paths
Node publishes all the module search paths to module.paths. We can traverse these and pick the first one that resolves.
async function getAppPath() {
const { dirname } = require('path');
const { constants, promises: { access } } = require('fs');
for (let path of module.paths) {
try {
await access(path, constants.F_OK);
return dirname(path);
} catch (e) {
// Just move on to next path
}
}
}
Pros & Cons
This will sometimes work, but is not reliable when used in a package because it may return the directory that the package is installed in rather than the directory that the application is installed in.
Using a global variable
Node has a global namespace object called global β€” anything that you attach to this object will be available everywhere in your app. So, in your index.js (or app.js or whatever your main app
file is named), you can just define a global variable:
// index.js
var path = require('path');
global.appRoot = path.resolve(__dirname);
// lib/moduleA/component1.js
require(appRoot + '/lib/moduleB/component2.js');
Pros & Cons
Works consistently, but you have to rely on a global variable, which means that you can't easily reuse components/etc.
process.cwd()
This returns the current working directory. Not reliable at all, as it's entirely dependent on what directory the process was launched from:
$ cd /home/demo/
$ mkdir subdir
$ echo "console.log(process.cwd());" > subdir/demo.js
$ node subdir/demo.js
/home/demo
$ cd subdir
$ node demo.js
/home/demo/subdir
app-root-path
To address this issue, I've created a node module called app-root-path. Usage is simple:
const appRoot = require('app-root-path');
const myModule = require(`${ appRoot }/lib/my-module.js`);
The app-root-path module uses several techniques to determine the root path of the app, taking into account globally installed modules (for example, if your app is running in /var/www/ but the module is installed in ~/.nvm/v0.x.x/lib/node/). It won't work 100% of the time, but it's going to work in most common scenarios.
Pros & Cons
Works without configuration in most circumstances. Also provides some nice additional convenience methods (see project page). The biggest con is that it won't work if:
You're using a launcher, like pm2
AND, the module isn't installed inside your app's node_modules directory (for example, if you installed it globally)
You can get around this by either setting a APP_ROOT_PATH environmental variable, or by calling .setPath() on the module, but in that case, you're probably better off using the global method.
NODE_PATH environmental variable
If you're looking for a way to determine the root path of the current app, one of the above solutions is likely to work best for you. If, on the other hand, you're trying to solve the problem of loading app modules reliably, I highly recommend looking into the NODE_PATH environmental variable.
Node's Modules system looks for modules in a variety of locations. One of these locations is wherever process.env.NODE_PATH points. If you set this environmental variable, then you can require modules with the standard module loader without any other changes.
For example, if you set NODE_PATH to /var/www/lib, the the following would work just fine:
require('module2/component.js');
// ^ looks for /var/www/lib/module2/component.js
A great way to do this is using npm:
{
"scripts": {
"start": "NODE_PATH=. node app.js"
}
}
Now you can start your app with npm start and you're golden. I combine this with my enforce-node-path module, which prevents accidentally loading the app without NODE_PATH set. For even more control over enforcing environmental variables, see checkenv.
One gotcha: NODE_PATH must be set outside of the node app. You cannot do something like process.env.NODE_PATH = path.resolve(__dirname) because the module loader caches the list of directories it will search before your app runs.
[added 4/6/16] Another really promising module that attempts to solve this problem is wavy.
__dirname isn't a global; it's local to the current module so each file has its own local, different value.
If you want the root directory of the running process, you probably do want to use process.cwd().
If you want predictability and reliability, then you probably need to make it a requirement of your application that a certain environment variable is set. Your app looks for MY_APP_HOME (Or whatever) and if it's there, and the application exists in that directory then all is well. If it is undefined or the directory doesn't contain your application then it should exit with an error prompting the user to create the variable. It could be set as a part of an install process.
You can read environment variables in node with something like process.env.MY_ENV_VARIABLE.
1- create a file in the project root call it settings.js
2- inside this file add this code
module.exports = {
POST_MAX_SIZE : 40 , //MB
UPLOAD_MAX_FILE_SIZE: 40, //MB
PROJECT_DIR : __dirname
};
3- inside node_modules create a new module name it "settings" and inside the module index.js write this code:
module.exports = require("../../settings");
4- and any time you want your project directory just use
var settings = require("settings");
settings.PROJECT_DIR;
in this way you will have all project directories relative to this file ;)
the easiest way to get the global root (assuming you use NPM to run your node.js app 'npm start', etc)
var appRoot = process.env.PWD;
If you want to cross-verify the above
Say you want to cross-check process.env.PWD with the settings of you node.js application. if you want some runtime tests to check the validity of process.env.PWD, you can cross-check it with this code (that I wrote which seems to work well). You can cross-check the name of the last folder in appRoot with the npm_package_name in your package.json file, for example:
var path = require('path');
var globalRoot = __dirname; //(you may have to do some substring processing if the first script you run is not in the project root, since __dirname refers to the directory that the file is in for which __dirname is called in.)
//compare the last directory in the globalRoot path to the name of the project in your package.json file
var folders = globalRoot.split(path.sep);
var packageName = folders[folders.length-1];
var pwd = process.env.PWD;
var npmPackageName = process.env.npm_package_name;
if(packageName !== npmPackageName){
throw new Error('Failed check for runtime string equality between globalRoot-bottommost directory and npm_package_name.');
}
if(globalRoot !== pwd){
throw new Error('Failed check for runtime string equality between globalRoot and process.env.PWD.');
}
you can also use this NPM module: require('app-root-path') which works very well for this purpose
Simple:
require('path').resolve('./')
As simple as adding this line to your module in the root, usually it is app.js or app.ts.
global.__basedir = __dirname;
Then _basedir will be accessible to all your modules.
Note: For typescript implementation, follow the above step and then you will be able to use the root directory path using global.__basedir
I've found this works consistently for me, even when the application is invoked from a sub-folder, as it can be with some test frameworks, like Mocha:
process.mainModule.paths[0].split('node_modules')[0].slice(0, -1);
Why it works:
At runtime node creates a registry of the full paths of all loaded files. The modules are loaded first, and thus at the top of this registry. By selecting the first element of the registry and returning the path before the 'node_modules' directory we are able to determine the root of the application.
It's just one line of code, but for simplicity's sake (my sake), I black boxed it into an NPM module:
https://www.npmjs.com/package/node-root.pddivine
Enjoy!
EDIT:
process.mainModule is deprecated as of v14.0.0
Use require.main instead:
require.main.paths[0].split('node_modules')[0].slice(0, -1);
Try traversing upwards from __dirname until you find a package.json, and decide that's the app main root directory your current file belongs to.
According to Node docs
The package.json file is normally located at the root directory of a Node.js project.
const fs = require('fs')
const path = require('path')
function getAppRootDir () {
let currentDir = __dirname
while(!fs.existsSync(path.join(currentDir, 'package.json'))) {
currentDir = path.join(currentDir, '..')
}
return currentDir
}
All these "root dirs" mostly need to resolve some virtual path to a real pile path, so may be you should look at path.resolve?
var path= require('path');
var filePath = path.resolve('our/virtual/path.ext');
Preamble
This is a very old question, but it seems to hit the nerve in 2020 as much as back in 2012.
I've checked all the other answers and could not find the following technique mentioned (it has its own limitations, but the others are not applicable to every situation either):
Git + child process
If you are using Git as your version control system, the problem of determining the project root can be reduced to (which I would consider the proper root of the project - after all, you would want your VCS to have the fullest visibility scope possible):
retrieve repository root path
Since you have to run a CLI command to do that, we need to spawn a child process. Additionally, as project root is highly unlikely to change mid-runtime, we can use the synchronous version of the child_process module at startup.
I found spawnSync() to be the most suitable for the job. As for the actual command to run, git worktree (with a --porcelain option for ease of parsing) is all that is needed to retrieve the absolute path of the root.
In the sample at the end of the answer, I opted to return an array of paths because there might be multiple worktrees (although they are likely to have common paths) just to be sure. Note that as we utilize a CLI command, shell option should be set to true (security shouldn't be an issue as there is no untrusted input).
Approach comparison and fallbacks
Understanding that a situation where VCS can be inaccessible is possible, I've included a couple of fallbacks after analyzing docs and other answers. The proposed solutions boil down to (excluding third-party modules & packages):
Solution
Advantage
Main Problem
__filename
points to module file
relative to module
__dirname
points to module dir
same as __filename
node_modules tree walk
nearly guaranteed root
complex tree walking if nested
path.resolve(".")
root if CWD is root
same as process.cwd()
process.argv\[1\]
same as __filename
same as __filename
process.env.INIT_CWD
points to npm run dir
requires npm && CLI launch
process.env.PWD
points to current dir
relative to (is the) launch dir
process.cwd()
same as env.PWD
process.chdir(path) at runtime
require.main.filename
root if === module
fails on required modules
From the comparison table above, the following approaches are the most universal:
require.main.filename as an easy way to get the root if require.main === module is met
node_modules tree walk proposed recently uses another assumption:
if the directory of the module has node_modules dir inside, it is likely to be the root
For the main app, it will get the app root and for a module β€” its project root.
Fallback 1. Tree walk
My implementation uses a more lax approach by stopping once a target directory is found as for a given module its root is the project root. One can chain the calls or extend it to make the search depth configurable:
/**
* #summary gets root by walking up node_modules
* #param {import("fs")} fs
* #param {import("path")} pt
*/
const getRootFromNodeModules = (fs, pt) =>
/**
* #param {string} [startPath]
* #returns {string[]}
*/
(startPath = __dirname) => {
//avoid loop if reached root path
if (startPath === pt.parse(startPath).root) {
return [startPath];
}
const isRoot = fs.existsSync(pt.join(startPath, "node_modules"));
if (isRoot) {
return [startPath];
}
return getRootFromNodeModules(fs, pt)(pt.dirname(startPath));
};
Fallback 2. Main module
The second implementation is trivial:
/**
* #summary gets app entry point if run directly
* #param {import("path")} pt
*/
const getAppEntryPoint = (pt) =>
/**
* #returns {string[]}
*/
() => {
const { main } = require;
const { filename } = main;
return main === module ?
[pt.parse(filename).dir] :
[];
};
Implementation
I would suggest using the tree walker as the preferred fallback because it is more versatile:
const { spawnSync } = require("child_process");
const pt = require('path');
const fs = require("fs");
/**
* #summary returns worktree root path(s)
* #param {function : string[] } [fallback]
* #returns {string[]}
*/
const getProjectRoot = (fallback) => {
const { error, stdout } = spawnSync(
`git worktree list --porcelain`,
{
encoding: "utf8",
shell: true
}
);
if (!stdout) {
console.warn(`Could not use GIT to find root:\n\n${error}`);
return fallback ? fallback() : [];
}
return stdout
.split("\n")
.map(line => {
const [key, value] = line.split(/\s+/) || [];
return key === "worktree" ? value : "";
})
.filter(Boolean);
};
Disadvantages
The most obvious one is having Git installed and initialized which might be undesirable/implausible (side note: having Git installed on production servers is not uncommon, nor is it unsafe). Can be mediated by fallbacks as described above.
There is an INIT_CWD property on process.env. This is what I'm currently working with in my project.
const {INIT_CWD} = process.env; // process.env.INIT_CWD
const paths = require(`${INIT_CWD}/config/paths`);
Good Luck...
A technique that I've found useful when using express is to add the following to app.js before any of your other routes are set
// set rootPath
app.use(function(req, res, next) {
req.rootPath = __dirname;
next();
});
app.use('/myroute', myRoute);
No need to use globals and you have the path of the root directory as a property of the request object.
This works if your app.js is in the root of your project which, by default, it is.
Actually, i find the perhaps trivial solution also to most robust:
you simply place the following file at the root directory of your project: root-path.js which has the following code:
import * as path from 'path'
const projectRootPath = path.resolve(__dirname)
export const rootPath = projectRootPath
Add this somewhere towards the start of your main app file (e.g. app.js):
global.__basedir = __dirname;
This sets a global variable that will always be equivalent to your app's base dir. Use it just like any other variable:
const yourModule = require(__basedir + '/path/to/module.js');
Simple...
I know this one is already too late.
But we can fetch root URL by two methods
1st method
var path = require('path');
path.dirname(require.main.filename);
2nd method
var path = require('path');
path.dirname(process.mainModule.filename);
Reference Link:- https://gist.github.com/geekiam/e2e3e0325abd9023d3a3
process.mainModule is deprecated since v 14.0.0. When referring to the answer, please use require.main, the rest still holds.
process.mainModule.paths
.filter(p => !p.includes('node_modules'))
.shift()
Get all paths in main modules and filter out those with "node_modules",
then get the first of remaining path list. Unexpected behavior will not throw error, just an undefined.
Works well for me, even when calling ie $ mocha.
At top of main file add:
mainDir = __dirname;
Then use it in any file you need:
console.log('mainDir ' + mainDir);
mainDir is defined globally, if you need it only in current file - use __dirname instead.
main file is usually in root folder of the project and is named like main.js, index.js, gulpfile.js.
if you want to determine project root from a running node.js application you can simply just too.
process.mainModule.path
It work for me
process.env.PWD
This will step down the directory tree until it contains a node_modules directory, which usually indicates your project root:
const fs = require('fs')
const path = require('path')
function getProjectRoot(currentDir = __dirname.split(path.sep)) {
if (!currentDir.length) {
throw Error('Could not find project root.')
}
const nodeModulesPath = currentDir.concat(['node_modules']).join(path.sep)
if (fs.existsSync(nodeModulesPath) && !currentDir.includes('node_modules')) {
return currentDir.join(path.sep)
}
return this.getProjectRoot(currentDir.slice(0, -1))
}
It also makes sure that there is no node_modules in the returned path, as that means that it is contained in a nested package install.
Create a function in app.js
/*Function to get the app root folder*/
var appRootFolder = function(dir,level){
var arr = dir.split('\\');
arr.splice(arr.length - level,level);
var rootFolder = arr.join('\\');
return rootFolder;
}
// view engine setup
app.set('views', path.join(appRootFolder(__dirname,1),'views'));
I use this.
For my module named mymodule
var BASE_DIR = __dirname.replace(/^(.*\/mymodule)(.*)$/, '$1')
Make it sexy πŸ’ƒπŸ».
const users = require('../../../database/users'); // πŸ‘Ž what you have
// OR
const users = require('$db/users'); // πŸ‘ no matter how deep you are
const products = require('/database/products'); // πŸ‘ alias or pathing from root directory
Three simple steps to solve the issue of ugly path.
Install the package: npm install sexy-require --save
Include require('sexy-require') once on the top of your main application file.
require('sexy-require');
const routers = require('/routers');
const api = require('$api');
...
Optional step. Path configuration can be defined in .paths file on root directory of your project.
$db = /server/database
$api-v1 = /server/api/legacy
$api-v2 = /server/api/v2
You can simply add the root directory path in the express app variable and get this path from the app. For this add app.set('rootDirectory', __dirname); in your index.js or app.js file. And use req.app.get('rootDirectory') for getting the root directory path in your code.
Old question, I know, however no question mention to use progress.argv. The argv array includes a full pathname and filename (with or without .js extension) that was used as parameter to be executed by node. Because this also can contain flags, you must filter this.
This is not an example you can directly use (because of using my own framework) but I think it gives you some idea how to do it. I also use a cache method to avoid that calling this function stress the system too much, especially when no extension is specified (and a file exist check is required), for example:
node myfile
or
node myfile.js
That's the reason I cache it, see also code below.
function getRootFilePath()
{
if( !isDefined( oData.SU_ROOT_FILE_PATH ) )
{
var sExt = false;
each( process.argv, function( i, v )
{
// Skip invalid and provided command line options
if( !!v && isValidString( v ) && v[0] !== '-' )
{
sExt = getFileExt( v );
if( ( sExt === 'js' ) || ( sExt === '' && fileExists( v+'.js' )) )
{
var a = uniformPath( v ).split("/");
// Chop off last string, filename
a[a.length-1]='';
// Cache it so we don't have to do it again.
oData.SU_ROOT_FILE_PATH=a.join("/");
// Found, skip loop
return true;
}
}
}, true ); // <-- true is: each in reverse order
}
return oData.SU_ROOT_FILE_PATH || '';
}
};
Finding the root path of an electron app could get tricky. Because the root path is different for the main process and renderer under different conditions such as production, development and packaged conditions.
I have written a npm package electron-root-path to capture the root path of an electron app.
$ npm install electron-root-path
or
$ yarn add electron-root-path
// Import ES6 way
import { rootPath } from 'electron-root-path';
// Import ES2015 way
const rootPath = require('electron-root-path').rootPath;
// e.g:
// read a file in the root
const location = path.join(rootPath, 'package.json');
const pkgInfo = fs.readFileSync(location, { encoding: 'utf8' });
This will do:
path.join(...process.argv[1].split(/\/|\\/).slice(0, -1))
path.dirname(process.mainModule.filename);
In modern versions of npm, you can add an entry to exports, to use as a shorthand. Note that if you want to be able to reference both the root itself and files within that root, you'll need both ./ and ./* respectively:
package.json:
{
"imports": {
"#root": "./",
"#root/*": "./*",
...
},
...
}
./index.js:
import {namedExport} from '#root/file.js'
./file.js:
export const namedExport = {
hi: "world",
};
Then:
$ node --experimental-specifier-resolution=node index.js
You could extend this further with a constants.js file, where you may use one of the methods in the above answers, or input an absolute path, should you require the path itself
You can also use
git rev-parse --show-toplevel
Assuming you are working on a git repository

Alternative for __dirname in Node.js when using ES6 modules

I use the flag --experimental-modules when running my Node application in order to use ES6 modules.
However when I use this flag the metavariable __dirname is not available. Is there an alternative way to get the same string that is stored in __dirname that is compatible with this mode?
As of Node.js 10.12 there's an alternative that doesn't require creating multiple files and handles special characters in filenames across platforms:
import { dirname } from 'path';
import { fileURLToPath } from 'url';
const __dirname = dirname(fileURLToPath(import.meta.url));
The most standardized way in 2021
import { URL } from 'url'; // in Browser, the URL in native accessible on window
const __filename = new URL('', import.meta.url).pathname;
// Will contain trailing slash
const __dirname = new URL('.', import.meta.url).pathname;
And forget about join to create paths from the current file, just use the URL
const pathToAdjacentFooFile = new URL('./foo.txt', import.meta.url).pathname;
const pathToUpperBarFile = new URL('../bar.json', import.meta.url).pathname;
For Node 10.12 +...
Assuming you are working from a module, this solution should work, and also gives you __filename support as well
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
The nice thing is that you are also only two lines of code away from supporting require() for CommonJS modules. For that you would add:
import { createRequireFromPath } from 'module';
const require = createRequireFromPath(__filename);
In most cases, using what is native to Node.js (with ES Modules), not external resources, the use of __filename and __dirname for most cases can be totally unnecessary. Most (if not all) of the native methods for reading (streaming) supports the new URL + import.meta.url, exactly as the official documentation itself suggests:
No __filename or __dirname
No JSON Module Loading
No require.resolve
As you can see in the description of the methods, the path parameter shows the supported formats, and in them include the <URL>, examples:
Method
path param supports
fs.readFile(path[, options], callback)
<string>, <Buffer>, <URL>, <integer>
fs.readFileSync(path[, options])
<string>, <Buffer>, <URL>, <integer>
fs.readdir(path[, options], callback)
<string>, <Buffer>, <URL>
fs.readdirSync(path[, options])
<string>, <Buffer>, <URL>, <integer>
fsPromises.readdir(path[, options])
<string>, <Buffer>, <URL>
fsPromises.readFile(path[, options])
<string>, <Buffer>, <URL>, <FileHandle>
So with new URL('<path or file>', import.meta.url) it solves and you don't need to be treating strings and creating variables to be concatenated later.
Examples:
See how it is possible to read a file at the same level as the script without needing __filename or any workaround:
import { readFileSync } from 'fs';
const output = readFileSync(new URL('./foo.txt', import.meta.url));
console.log(output.toString());
List all files in the script directory:
import { readdirSync } from 'fs';
readdirSync(new URL('./', import.meta.url)).forEach((dirContent) => {
console.log(dirContent);
});
Note: In the examples I used the synchronous functions just to make it easier to copy and execute.
If the intention is to make a "own log" (or something similar) that will depend on third parties, it is worth some things done manually, but within the language and Node.js this is not necessary, with ESMODULES it is totally possible not to depend on either __filename and neither __dirname, since native resources with new URL with already solve it.
Note that if you are interested in using something like require at strategic times and need the absolute path from the main script, you can use module.createRequire(filename) (Node.js v12.2.0 + only) combined with import.meta.url to load scripts at levels other than the current script level, as this already helps to avoid the need for __dirname, an example using import.meta.url with module.createRequire:
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
// foo-bar.js is a CommonJS module.
const fooBar = require('./foo-bar');
fooBar();
Source from foo-bar.js:
module.exports = () => {
console.log('hello world!');
};
Which is similar to using without "ECMAScript modules":
const fooBar = require('./foo-bar');
There have been proposals about exposing these variables through import.meta, but for now, you need a hacky workaround that I found here:
// expose.js
module.exports = {__dirname};
// use.mjs
import expose from './expose.js';
const {__dirname} = expose;
I used:
import path from 'path';
const __dirname = path.resolve(path.dirname(decodeURI(new URL(import.meta.url).pathname)));
decodeURI was important: used spaces and other stuff within the path on my test system.
path.resolve() handles relative urls.
edit:
fix to support windows (/C:/... => C:/...):
import path from 'path';
const __dirname = (() => {let x = path.dirname(decodeURI(new URL(import.meta.url).pathname)); return path.resolve( (process.platform == "win32") ? x.substr(1) : x ); })();
I made this module es-dirname that will return the current script dirname.
import dirname from 'es-dirname'
console.log(dirname())
It works both in CommonJs scripts and in ES Modules both on Windows and Linux.
Open an issue there if have an error as the script has been working so far in my projects but it might fail in some other cases. For this reason do not use it in a production environment. And this is a temporary solution as I am sure the Node.js team will release a robust way to do it in a near future.
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// do not use the following code which is bad for CJK characters
const __filename = new URL('', import.meta.url).pathname;
import path from 'path';
const __dirname = path.join(path.dirname(decodeURI(new URL(import.meta.url).pathname))).replace(/^\\([A-Z]:\\)/, "$1");
This code also works on Windows. (the replacement is safe on other platforms, since path.join returns back-slash separators only on Windows)
Since other answers, while useful, don't cover both cross-platform cases (Windows POSIX) and/or path resolution other than the __dirname or __filename and it's kind of verbose to repeat this kind of code everywhere:
import { dirname, join } from 'path'
import { fileURLToPath } from 'url'
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
const somePath = join(__dirname, '../some-dir-or-some-file')
I just published a NPM package called esm-path to help with this kind of recurring task, hoping it can also be useful to others.
It's documented but here how to use it:
import { getAbsolutePath } from 'esm-path'
const currentDirectoryPath = getAbsolutePath(import.meta.url)
console.log(currentDirectoryPath)
const parentDirectoryPath = getAbsolutePath(import.meta.url, '..')
console.log(parentDirectoryPath)
// Adapt the relative path to your case
const packageJsonFilePath = getAbsolutePath(import.meta.url, '../package.json')
console.log(packageJsonFilePath)
// Adapt the relative path to your case
const packageJsonFilePath = getAbsolutePath(import.meta.url, '..' , 'package.json')
console.log(packageJsonFilePath)
Just use path.resolve() method.
import { resolve } from 'path';
app.use('/public/uploads', express.static(resolve('public', 'uploads')))
I use this option, since the path starts with file:// just remove that part.
const __filename = import.meta.url.slice(7);
const __dirname = import.meta.url.slice(7, import.meta.url.lastIndexOf("/"));
As Geoff pointed out the following code returns not the module's path but working directory.
import path from 'path';
const __dirname = path.resolve();
works with --experimental-modules
create a file called root-dirname.js in your project root with this in it:
import { dirname } from 'path'
const dn = dirname(new URL(import.meta.url).hostname)
const __dirname = process.platform === 'win32' ? dn.substr(1) : dn // remove the leading slash on Windows
export const rootDirname = __dirname
Then just import rootDirname when you want the path to the project root folder.
Other than that, Rudolf GrΓΆhling's answer is also correct.
You can use the stack from a new Error(). The error doesn't need to be thrown, and won't stop program execution either. The first line of the stack will always be the error and its message, with the second line being the file the which the error was invoked from.
Since this is a method (which is probably in a util.js file), the real location of the getDirname() call is actually the third line of the error stack.
export const getDirname = () => {
// get the stack
const { stack } = new Error();
// get the third line (the original invoker)
const invokeFileLine = stack.split(`\n`)[2];
// match the file URL from file://(.+)/ and get the first capturing group
// the (.+) is a greedy quantifier and will make the RegExp expand to the largest match
const __dirname = invokeFileLine.match(/file:\/\/(.+)\//)[1];
return __dirname;
};
another option
import {createRequire} from 'module'; // need node v12.2.0
const require = createRequire(import.meta.url);
const __dirname = require.resolve.paths('.')[0];
I have also published a package on NPM called cross-dirname (forked from es-dirname). The package is tested with Node.js (ESM and CJS), Deno and GJS.
Example:
import dirname from 'cross-dirname'
console.log(dirname())
Agree or disagree with the use of global, I found this to be the easiest way to remember and refactor existing code.
Put somewhere early in your code execution:
import { fileURLToPath } from 'node:url';
import { dirname } from 'node:path';
global.___filename = (path) => {
return fileURLToPath(path);
};
global.___dirname = (path) => {
return dirname(global.___filename(path));
};
And then in whichever file you need dirname or filename:
___filename(import.meta.url)
___dirname(import.meta.url)
Of course if we had macros, I wouldn't need to pass import.meta.url, perhaps there's an improvement.
process.cwd()
From documentation:
The process.cwd() method returns the current working directory of the
Node.js process.

Nodejs get absolute path relative to process.cwd()

So I have the following code block:
#!/usr/bin/env node
const path = require('path');
const yargs = require('yargs').argv;
const ghpages = require('gh-pages');
const randomstring = require("randomstring");
const dirName = randomstring.generate({
length: 12,
charset: 'alphabetic'
});
console.log(__dirname, dirName, process.cwd(), yargs.directory, yargs.branch);
ghpages.publish(path.join(process.cwd(), yargs.directory), {
branch: yargs.branch,
clone: `../../../../tmp/${dirName}`
}, () => {
console.log('removing');
});
This requires an absolute path to the clone location.
Obviously I have hard coded it at the moment for testing but what I want to do is get the absolute path to /tmp/ from the process.cwd().
So basically what I want is if I ran the script in /home/otis ../../../../tmp/${dirName} would become ../../tmp/${dirName} so I need to generate the path based on the process.cwd()
Any ideas?
Cheers/
You can use path.resolve to get the absolute path.
e.g.
path.resolve('../src/tmp')
// '/Users/yourusername/src/tmp'
Or you can use the path.relative( from, to ) which gives the relative path between from and to
So in your case, I guess it is
path.relative( process.cwd(), "../../../../tmp/" )
It's bad practice to use relative paths, especially to system folders. In case if a project location will be changed, you will have to update your code as well.
If you need the system temp directory, you can use the following:
require('os').tmpdir()
It will return you correct absolute path to your temporary folder depending on current OS.

Determine project root from a running node.js application

Is there a different way, other than process.cwd(), to get the pathname of the current project's root-directory. Does Node implement something like ruby's property, Rails.root,. I'm looking for something that is constant, and reliable.
There are many ways to approach this, each with their own pros and cons:
require.main.filename
From http://nodejs.org/api/modules.html:
When a file is run directly from Node, require.main is set to its module. That means that you can determine whether a file has been run directly by testing require.main === module
Because module provides a filename property (normally equivalent to __filename), the entry point of the current application can be obtained by checking require.main.filename.
So if you want the base directory for your app, you can do:
const { dirname } = require('path');
const appDir = dirname(require.main.filename);
Pros & Cons
This will work great most of the time, but if you're running your app with a launcher like pm2 or running mocha tests, this method will fail. This also won't work when using Node.js ES modules, where require.main is not available.
module.paths
Node publishes all the module search paths to module.paths. We can traverse these and pick the first one that resolves.
async function getAppPath() {
const { dirname } = require('path');
const { constants, promises: { access } } = require('fs');
for (let path of module.paths) {
try {
await access(path, constants.F_OK);
return dirname(path);
} catch (e) {
// Just move on to next path
}
}
}
Pros & Cons
This will sometimes work, but is not reliable when used in a package because it may return the directory that the package is installed in rather than the directory that the application is installed in.
Using a global variable
Node has a global namespace object called global β€” anything that you attach to this object will be available everywhere in your app. So, in your index.js (or app.js or whatever your main app
file is named), you can just define a global variable:
// index.js
var path = require('path');
global.appRoot = path.resolve(__dirname);
// lib/moduleA/component1.js
require(appRoot + '/lib/moduleB/component2.js');
Pros & Cons
Works consistently, but you have to rely on a global variable, which means that you can't easily reuse components/etc.
process.cwd()
This returns the current working directory. Not reliable at all, as it's entirely dependent on what directory the process was launched from:
$ cd /home/demo/
$ mkdir subdir
$ echo "console.log(process.cwd());" > subdir/demo.js
$ node subdir/demo.js
/home/demo
$ cd subdir
$ node demo.js
/home/demo/subdir
app-root-path
To address this issue, I've created a node module called app-root-path. Usage is simple:
const appRoot = require('app-root-path');
const myModule = require(`${ appRoot }/lib/my-module.js`);
The app-root-path module uses several techniques to determine the root path of the app, taking into account globally installed modules (for example, if your app is running in /var/www/ but the module is installed in ~/.nvm/v0.x.x/lib/node/). It won't work 100% of the time, but it's going to work in most common scenarios.
Pros & Cons
Works without configuration in most circumstances. Also provides some nice additional convenience methods (see project page). The biggest con is that it won't work if:
You're using a launcher, like pm2
AND, the module isn't installed inside your app's node_modules directory (for example, if you installed it globally)
You can get around this by either setting a APP_ROOT_PATH environmental variable, or by calling .setPath() on the module, but in that case, you're probably better off using the global method.
NODE_PATH environmental variable
If you're looking for a way to determine the root path of the current app, one of the above solutions is likely to work best for you. If, on the other hand, you're trying to solve the problem of loading app modules reliably, I highly recommend looking into the NODE_PATH environmental variable.
Node's Modules system looks for modules in a variety of locations. One of these locations is wherever process.env.NODE_PATH points. If you set this environmental variable, then you can require modules with the standard module loader without any other changes.
For example, if you set NODE_PATH to /var/www/lib, the the following would work just fine:
require('module2/component.js');
// ^ looks for /var/www/lib/module2/component.js
A great way to do this is using npm:
{
"scripts": {
"start": "NODE_PATH=. node app.js"
}
}
Now you can start your app with npm start and you're golden. I combine this with my enforce-node-path module, which prevents accidentally loading the app without NODE_PATH set. For even more control over enforcing environmental variables, see checkenv.
One gotcha: NODE_PATH must be set outside of the node app. You cannot do something like process.env.NODE_PATH = path.resolve(__dirname) because the module loader caches the list of directories it will search before your app runs.
[added 4/6/16] Another really promising module that attempts to solve this problem is wavy.
__dirname isn't a global; it's local to the current module so each file has its own local, different value.
If you want the root directory of the running process, you probably do want to use process.cwd().
If you want predictability and reliability, then you probably need to make it a requirement of your application that a certain environment variable is set. Your app looks for MY_APP_HOME (Or whatever) and if it's there, and the application exists in that directory then all is well. If it is undefined or the directory doesn't contain your application then it should exit with an error prompting the user to create the variable. It could be set as a part of an install process.
You can read environment variables in node with something like process.env.MY_ENV_VARIABLE.
1- create a file in the project root call it settings.js
2- inside this file add this code
module.exports = {
POST_MAX_SIZE : 40 , //MB
UPLOAD_MAX_FILE_SIZE: 40, //MB
PROJECT_DIR : __dirname
};
3- inside node_modules create a new module name it "settings" and inside the module index.js write this code:
module.exports = require("../../settings");
4- and any time you want your project directory just use
var settings = require("settings");
settings.PROJECT_DIR;
in this way you will have all project directories relative to this file ;)
the easiest way to get the global root (assuming you use NPM to run your node.js app 'npm start', etc)
var appRoot = process.env.PWD;
If you want to cross-verify the above
Say you want to cross-check process.env.PWD with the settings of you node.js application. if you want some runtime tests to check the validity of process.env.PWD, you can cross-check it with this code (that I wrote which seems to work well). You can cross-check the name of the last folder in appRoot with the npm_package_name in your package.json file, for example:
var path = require('path');
var globalRoot = __dirname; //(you may have to do some substring processing if the first script you run is not in the project root, since __dirname refers to the directory that the file is in for which __dirname is called in.)
//compare the last directory in the globalRoot path to the name of the project in your package.json file
var folders = globalRoot.split(path.sep);
var packageName = folders[folders.length-1];
var pwd = process.env.PWD;
var npmPackageName = process.env.npm_package_name;
if(packageName !== npmPackageName){
throw new Error('Failed check for runtime string equality between globalRoot-bottommost directory and npm_package_name.');
}
if(globalRoot !== pwd){
throw new Error('Failed check for runtime string equality between globalRoot and process.env.PWD.');
}
you can also use this NPM module: require('app-root-path') which works very well for this purpose
Simple:
require('path').resolve('./')
As simple as adding this line to your module in the root, usually it is app.js or app.ts.
global.__basedir = __dirname;
Then _basedir will be accessible to all your modules.
Note: For typescript implementation, follow the above step and then you will be able to use the root directory path using global.__basedir
I've found this works consistently for me, even when the application is invoked from a sub-folder, as it can be with some test frameworks, like Mocha:
process.mainModule.paths[0].split('node_modules')[0].slice(0, -1);
Why it works:
At runtime node creates a registry of the full paths of all loaded files. The modules are loaded first, and thus at the top of this registry. By selecting the first element of the registry and returning the path before the 'node_modules' directory we are able to determine the root of the application.
It's just one line of code, but for simplicity's sake (my sake), I black boxed it into an NPM module:
https://www.npmjs.com/package/node-root.pddivine
Enjoy!
EDIT:
process.mainModule is deprecated as of v14.0.0
Use require.main instead:
require.main.paths[0].split('node_modules')[0].slice(0, -1);
Try traversing upwards from __dirname until you find a package.json, and decide that's the app main root directory your current file belongs to.
According to Node docs
The package.json file is normally located at the root directory of a Node.js project.
const fs = require('fs')
const path = require('path')
function getAppRootDir () {
let currentDir = __dirname
while(!fs.existsSync(path.join(currentDir, 'package.json'))) {
currentDir = path.join(currentDir, '..')
}
return currentDir
}
All these "root dirs" mostly need to resolve some virtual path to a real pile path, so may be you should look at path.resolve?
var path= require('path');
var filePath = path.resolve('our/virtual/path.ext');
Preamble
This is a very old question, but it seems to hit the nerve in 2020 as much as back in 2012.
I've checked all the other answers and could not find the following technique mentioned (it has its own limitations, but the others are not applicable to every situation either):
Git + child process
If you are using Git as your version control system, the problem of determining the project root can be reduced to (which I would consider the proper root of the project - after all, you would want your VCS to have the fullest visibility scope possible):
retrieve repository root path
Since you have to run a CLI command to do that, we need to spawn a child process. Additionally, as project root is highly unlikely to change mid-runtime, we can use the synchronous version of the child_process module at startup.
I found spawnSync() to be the most suitable for the job. As for the actual command to run, git worktree (with a --porcelain option for ease of parsing) is all that is needed to retrieve the absolute path of the root.
In the sample at the end of the answer, I opted to return an array of paths because there might be multiple worktrees (although they are likely to have common paths) just to be sure. Note that as we utilize a CLI command, shell option should be set to true (security shouldn't be an issue as there is no untrusted input).
Approach comparison and fallbacks
Understanding that a situation where VCS can be inaccessible is possible, I've included a couple of fallbacks after analyzing docs and other answers. The proposed solutions boil down to (excluding third-party modules & packages):
Solution
Advantage
Main Problem
__filename
points to module file
relative to module
__dirname
points to module dir
same as __filename
node_modules tree walk
nearly guaranteed root
complex tree walking if nested
path.resolve(".")
root if CWD is root
same as process.cwd()
process.argv\[1\]
same as __filename
same as __filename
process.env.INIT_CWD
points to npm run dir
requires npm && CLI launch
process.env.PWD
points to current dir
relative to (is the) launch dir
process.cwd()
same as env.PWD
process.chdir(path) at runtime
require.main.filename
root if === module
fails on required modules
From the comparison table above, the following approaches are the most universal:
require.main.filename as an easy way to get the root if require.main === module is met
node_modules tree walk proposed recently uses another assumption:
if the directory of the module has node_modules dir inside, it is likely to be the root
For the main app, it will get the app root and for a module β€” its project root.
Fallback 1. Tree walk
My implementation uses a more lax approach by stopping once a target directory is found as for a given module its root is the project root. One can chain the calls or extend it to make the search depth configurable:
/**
* #summary gets root by walking up node_modules
* #param {import("fs")} fs
* #param {import("path")} pt
*/
const getRootFromNodeModules = (fs, pt) =>
/**
* #param {string} [startPath]
* #returns {string[]}
*/
(startPath = __dirname) => {
//avoid loop if reached root path
if (startPath === pt.parse(startPath).root) {
return [startPath];
}
const isRoot = fs.existsSync(pt.join(startPath, "node_modules"));
if (isRoot) {
return [startPath];
}
return getRootFromNodeModules(fs, pt)(pt.dirname(startPath));
};
Fallback 2. Main module
The second implementation is trivial:
/**
* #summary gets app entry point if run directly
* #param {import("path")} pt
*/
const getAppEntryPoint = (pt) =>
/**
* #returns {string[]}
*/
() => {
const { main } = require;
const { filename } = main;
return main === module ?
[pt.parse(filename).dir] :
[];
};
Implementation
I would suggest using the tree walker as the preferred fallback because it is more versatile:
const { spawnSync } = require("child_process");
const pt = require('path');
const fs = require("fs");
/**
* #summary returns worktree root path(s)
* #param {function : string[] } [fallback]
* #returns {string[]}
*/
const getProjectRoot = (fallback) => {
const { error, stdout } = spawnSync(
`git worktree list --porcelain`,
{
encoding: "utf8",
shell: true
}
);
if (!stdout) {
console.warn(`Could not use GIT to find root:\n\n${error}`);
return fallback ? fallback() : [];
}
return stdout
.split("\n")
.map(line => {
const [key, value] = line.split(/\s+/) || [];
return key === "worktree" ? value : "";
})
.filter(Boolean);
};
Disadvantages
The most obvious one is having Git installed and initialized which might be undesirable/implausible (side note: having Git installed on production servers is not uncommon, nor is it unsafe). Can be mediated by fallbacks as described above.
There is an INIT_CWD property on process.env. This is what I'm currently working with in my project.
const {INIT_CWD} = process.env; // process.env.INIT_CWD
const paths = require(`${INIT_CWD}/config/paths`);
Good Luck...
A technique that I've found useful when using express is to add the following to app.js before any of your other routes are set
// set rootPath
app.use(function(req, res, next) {
req.rootPath = __dirname;
next();
});
app.use('/myroute', myRoute);
No need to use globals and you have the path of the root directory as a property of the request object.
This works if your app.js is in the root of your project which, by default, it is.
Actually, i find the perhaps trivial solution also to most robust:
you simply place the following file at the root directory of your project: root-path.js which has the following code:
import * as path from 'path'
const projectRootPath = path.resolve(__dirname)
export const rootPath = projectRootPath
Add this somewhere towards the start of your main app file (e.g. app.js):
global.__basedir = __dirname;
This sets a global variable that will always be equivalent to your app's base dir. Use it just like any other variable:
const yourModule = require(__basedir + '/path/to/module.js');
Simple...
I know this one is already too late.
But we can fetch root URL by two methods
1st method
var path = require('path');
path.dirname(require.main.filename);
2nd method
var path = require('path');
path.dirname(process.mainModule.filename);
Reference Link:- https://gist.github.com/geekiam/e2e3e0325abd9023d3a3
process.mainModule is deprecated since v 14.0.0. When referring to the answer, please use require.main, the rest still holds.
process.mainModule.paths
.filter(p => !p.includes('node_modules'))
.shift()
Get all paths in main modules and filter out those with "node_modules",
then get the first of remaining path list. Unexpected behavior will not throw error, just an undefined.
Works well for me, even when calling ie $ mocha.
At top of main file add:
mainDir = __dirname;
Then use it in any file you need:
console.log('mainDir ' + mainDir);
mainDir is defined globally, if you need it only in current file - use __dirname instead.
main file is usually in root folder of the project and is named like main.js, index.js, gulpfile.js.
if you want to determine project root from a running node.js application you can simply just too.
process.mainModule.path
It work for me
process.env.PWD
This will step down the directory tree until it contains a node_modules directory, which usually indicates your project root:
const fs = require('fs')
const path = require('path')
function getProjectRoot(currentDir = __dirname.split(path.sep)) {
if (!currentDir.length) {
throw Error('Could not find project root.')
}
const nodeModulesPath = currentDir.concat(['node_modules']).join(path.sep)
if (fs.existsSync(nodeModulesPath) && !currentDir.includes('node_modules')) {
return currentDir.join(path.sep)
}
return this.getProjectRoot(currentDir.slice(0, -1))
}
It also makes sure that there is no node_modules in the returned path, as that means that it is contained in a nested package install.
Create a function in app.js
/*Function to get the app root folder*/
var appRootFolder = function(dir,level){
var arr = dir.split('\\');
arr.splice(arr.length - level,level);
var rootFolder = arr.join('\\');
return rootFolder;
}
// view engine setup
app.set('views', path.join(appRootFolder(__dirname,1),'views'));
I use this.
For my module named mymodule
var BASE_DIR = __dirname.replace(/^(.*\/mymodule)(.*)$/, '$1')
Make it sexy πŸ’ƒπŸ».
const users = require('../../../database/users'); // πŸ‘Ž what you have
// OR
const users = require('$db/users'); // πŸ‘ no matter how deep you are
const products = require('/database/products'); // πŸ‘ alias or pathing from root directory
Three simple steps to solve the issue of ugly path.
Install the package: npm install sexy-require --save
Include require('sexy-require') once on the top of your main application file.
require('sexy-require');
const routers = require('/routers');
const api = require('$api');
...
Optional step. Path configuration can be defined in .paths file on root directory of your project.
$db = /server/database
$api-v1 = /server/api/legacy
$api-v2 = /server/api/v2
You can simply add the root directory path in the express app variable and get this path from the app. For this add app.set('rootDirectory', __dirname); in your index.js or app.js file. And use req.app.get('rootDirectory') for getting the root directory path in your code.
Old question, I know, however no question mention to use progress.argv. The argv array includes a full pathname and filename (with or without .js extension) that was used as parameter to be executed by node. Because this also can contain flags, you must filter this.
This is not an example you can directly use (because of using my own framework) but I think it gives you some idea how to do it. I also use a cache method to avoid that calling this function stress the system too much, especially when no extension is specified (and a file exist check is required), for example:
node myfile
or
node myfile.js
That's the reason I cache it, see also code below.
function getRootFilePath()
{
if( !isDefined( oData.SU_ROOT_FILE_PATH ) )
{
var sExt = false;
each( process.argv, function( i, v )
{
// Skip invalid and provided command line options
if( !!v && isValidString( v ) && v[0] !== '-' )
{
sExt = getFileExt( v );
if( ( sExt === 'js' ) || ( sExt === '' && fileExists( v+'.js' )) )
{
var a = uniformPath( v ).split("/");
// Chop off last string, filename
a[a.length-1]='';
// Cache it so we don't have to do it again.
oData.SU_ROOT_FILE_PATH=a.join("/");
// Found, skip loop
return true;
}
}
}, true ); // <-- true is: each in reverse order
}
return oData.SU_ROOT_FILE_PATH || '';
}
};
Finding the root path of an electron app could get tricky. Because the root path is different for the main process and renderer under different conditions such as production, development and packaged conditions.
I have written a npm package electron-root-path to capture the root path of an electron app.
$ npm install electron-root-path
or
$ yarn add electron-root-path
// Import ES6 way
import { rootPath } from 'electron-root-path';
// Import ES2015 way
const rootPath = require('electron-root-path').rootPath;
// e.g:
// read a file in the root
const location = path.join(rootPath, 'package.json');
const pkgInfo = fs.readFileSync(location, { encoding: 'utf8' });
This will do:
path.join(...process.argv[1].split(/\/|\\/).slice(0, -1))
path.dirname(process.mainModule.filename);
In modern versions of npm, you can add an entry to exports, to use as a shorthand. Note that if you want to be able to reference both the root itself and files within that root, you'll need both ./ and ./* respectively:
package.json:
{
"imports": {
"#root": "./",
"#root/*": "./*",
...
},
...
}
./index.js:
import {namedExport} from '#root/file.js'
./file.js:
export const namedExport = {
hi: "world",
};
Then:
$ node --experimental-specifier-resolution=node index.js
You could extend this further with a constants.js file, where you may use one of the methods in the above answers, or input an absolute path, should you require the path itself
You can also use
git rev-parse --show-toplevel
Assuming you are working on a git repository

Resources