Check whether script is Node or Phantom - node.js

I have a common module, providing the common directories for my project, which is used by both NodeJS and PhantomJS scripts. Anyone is aware of a simple clear function on how to return which script is running, if node.js or phantom.js?
For now, I use this method, but I don't know if it is the best approach
//parent directory of project directory tree
//tries to get according to Engine, Node or PhantomJS
var ROOT_DIR;
if (typeof __dirname !== 'undefined'){//nodeJS has __dirname
ROOT_DIR = path.resolve(__dirname, '.') + "/";
console.log("ROOT_DIR got on Node: " + ROOT_DIR);
}
else {//PhantomJS?
try{
var fs = require('fs');
ROOT_DIR = fs.absolute("./"); //it already leaves a trailing slash
console.log("ROOT_DIR got PhantomJS: " + ROOT_DIR);
}
catch(err){
throw "Engine not recognized, nor NodeJS nor PhantomJS";
}
}
Edit: this issue is slightly different from merely detecting node, since here we try also to detect PhantomJS, i.e., the difference is not between node and a browser but between node and phantomjs. Of course that the detection of node is similar, but many approaches to detect whether node is running or not, might in PhantomJS throw an exception.

Could this work?
const isNode = () => {
return process && process.argv[0] === 'node';
};

I used this to detect whether is nodeJS
if ((typeof process !== 'undefined') &&
(process.release.name.search(/node|io.js/) !== -1)){//node
}
else{//not node, im my case PhantomJS
}
It uses the node process object and since other modules might have that object name, within it it assures that attribute process.release.name has 'node' or 'io.js' within it.

Related

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

modify nodejs require() to search for .min.js

O/S is ubuntu 16, node version is 4.2.6.
I have source / development code and run / distribution code, the source.js files are minified and mangled to create equivalent source.min.js files, and I would like for node js require to automatically search for .min.js files as well as .js files.
But as I have a lot of files, I would prefer not to have to go through every require in every file and instead modify the built-in require() function.
This is a very simple implementation of a stand alone function, but how can I modify the built-in function to behave the same way ?
function require(file){
try{return require(file)}
catch(e){return require(file+='.min.js')}
}
You can achieve this by modifying prototype function require of Module class and apply it globally
Here is how you can do it :
var pathModule = require('path');
var assert = require('assert').ok;
module.constructor.prototype.require = function (path) {
var self = this;
assert(typeof path === 'string', 'path must be a string');
assert(path, 'missing path');
try {
return self.constructor._load(path, self);
} catch (err) {
// if module not found, we have nothing to do, simply throw it back.
if (err.code === 'MODULE_NOT_FOUND') {
throw err;
}
// resolve the path to get absolute path
path = pathModule.resolve(__dirname, path+".min.js")
// Write to log or whatever
console.log('Error in file: ' + path);
}
}

Path resolution issues with NPM modules vs apps

I am writing a module that will be used as a dependency for Node.js apps. In some cases, it will be a dependency of a dependency, which means the path resolution will change, and currently I am having a problem with that. Namely, when my module is a dependency of a dependency, my module will still look to the app root, not the root of the dependency.
I think the shortest way to ask a question on how to solve this is to find out the best way to determine if the module is a dependency or not.
So the way to do that would be to get the __dirname of the file in the index of my module and then navigate up one directory to see if that directory is named node_modules.
Is there a better way to do this? Is there a better way to determine if the code being invoked is being invoked from a dependency of the app or from the app itself?
Visually speaking, it looks like this
--app
---/node_modules
-----/A
-----/B
my module is called A
A could be used by app, or it could be used by B
if it's used by app, I can use the app-root-path module to quickly determine the root. But if my module is used by B, how will I know that? It will matter for resolving paths.
Here is the entiriety of the code in my module:
var appRoot = require('app-root-path');
var path = require('path');
var configs = {};
function checkIfDependency(){
var temp = path.resolve(path.normalize(__dirname + '/../'));
return path.basename(temp) === 'node_modules';
}
module.exports = function (identifier, pathToProvider) {
if (String(identifier).indexOf('*') < 0) {
throw new Error('did not pass in an identifier to univ-config');
}
if (configs[identifier]) {
return configs[identifier];
}
else {
if (pathToProvider) {
try {
var configPath;
if (path.isAbsolute(pathToProvider)) { //consumer of this lib has been so kind as to provide an absolute path, the risk is now yours
configPath = path.normalize(pathToProvider);
}
else if(checkIfDependency()){ //univ-config is being invoked from a dependency
configPath = path.normalize(??? + '/' + pathToProvider);
}
else{ //univ-config is being invoked from an app
configPath = path.normalize(appRoot + '/' + pathToProvider);
}
var f = require(configPath);
return configs[identifier] = f();
}
catch (err) {
throw new Error('univ-config could not resolve the path to your config provider module - given as:' + pathToProvider);
}
}
else {
throw new Error('no config matched the identifier but no path to config provider was passed to univ-config');
}
}
};

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

Detect if called through require or directly by command line

How can I detect whether my Node.JS file was called using SH:node path-to-file or JS:require('path-to-file')?
This is the Node.JS equivalent to my previous question in Perl: How can I run my Perl script only if it wasn't loaded with require?
if (require.main === module) {
console.log('called directly');
} else {
console.log('required as a module');
}
See documentation for this here: https://nodejs.org/docs/latest/api/modules.html#modules_accessing_the_main_module
There is another, slightly shorter way (not outlined in the mentioned docs).
var runningAsScript = !module.parent;
I outlined more details about how this all works under the hood in this blog post.
For those using ES Modules (and Node 10.12+), you can use import.meta.url:
import path from 'path';
import { fileURLToPath } from 'url'
const nodePath = path.resolve(process.argv[1]);
const modulePath = path.resolve(fileURLToPath(import.meta.url))
const isRunningDirectlyViaCLI = nodePath === modulePath
Things like require.main, module.parent and __dirname/__filename aren’t available in ESM.
Note: If using ESLint it may choke on this syntax, in which case you’ll need to update to ESLint ^7.2.0 and turn your ecmaVersion up to 11 (2020).
More info: process.argv, import.meta.url
I was a little confused by the terminology used in the explanation(s). So I had to do a couple quick tests.
I found that these produce the same results:
var isCLI = !module.parent;
var isCLI = require.main === module;
And for the other confused people (and to answer the question directly):
var isCLI = require.main === module;
var wasRequired = !isCLI;
Try this if you are using ES6 modules:
if (process.mainModule.filename === __filename) {
console.log('running as main module')
}
I always find myself trying to recall how to write this goddamn code snippet, so I decided to create a simple module for it. It took me a bit to make it work since accessing caller's module info is not straightforward, but it was fun to see how it could be done.
So the idea is to call a module and ask it if the caller module is the main one. We have to figure out the module of the caller function. My first approach was a variation of the accepted answer:
module.exports = function () {
return require.main === module.parent;
};
But that is not guaranteed to work. module.parent points to the module which loaded us into memory, not the one calling us. If it is the caller module that loaded this helper module into memory, we're good. But if it isn't, it won't work. So we need to try something else. My solution was to generate a stack trace and get the caller's module name from there:
module.exports = function () {
// generate a stack trace
const stack = (new Error()).stack;
// the third line refers to our caller
const stackLine = stack.split("\n")[2];
// extract the module name from that line
const callerModuleName = /\((.*):\d+:\d+\)$/.exec(stackLine)[1];
return require.main.filename === callerModuleName;
};
Save this as is-main-module.js and now you can do:
const isMainModule = require("./is-main-module");
if (isMainModule()) {
console.info("called directly");
} else {
console.info("required as a module");
}
Which is easier to remember.
First, let's define the problem better. My assumption is that what you are really looking for is whether your script owns process.argv (i.e. whether your script is responsible for processing process.argv). With this assumption in mind, the code and tests below are accurate.
module.parent works excellently, but it is deprecated for good reasons (a module might have multiple parents, in which case module.parent only represents the first parent), so use the following future-proof condition to cover all cases:
if (
typeof process === 'object' && process && process.argv
&& (
(
typeof module === 'object' && module
&& (
!module.parent
|| require.main === module
|| (process.mainModule && process.mainModule.filename === __filename)
|| (__filename === "[stdin]" && __dirname === ".")
)
)
|| (
typeof document === "object"
&& (function() {
var scripts = document.getElementsByTagName("script");
try { // in case we are in a special environment without path
var normalize = require("path").normalize;
for (var i=0,len=scripts.length|0; i < len; i=i+1|0)
if (normalize(scripts[i].src.replace(/^file:/i,"")) === __filename)
return true;
} catch(e) {}
})()
)
)
) {
// this module is top-level and invoked directly by the CLI
console.log("Invoked from CLI");
} else {
console.log("Not invoked from CLI");
}
It works correctly in all of the scripts in all of the following cases and never throws any errors†:
Requiring the script (e.x. require('./main.js'))
Directly invoking the script (e.x. nodejs cli.js)
Preloading another script (e.x. nodejs -r main.js cli.js)
Piping into node CLI (e.x. cat cli.js | nodejs)
Piping with preloading (e.x. cat cli.js | nodejs -r main.js)
In workers (e.x. new Worker('./worker.js'))
In evaled workers (e.x. new Worker('if (<test for CLI>) ...', {eval: true}))
Inside ES6 modules (e.x. nodejs --experimental-modules cli-es6.js)
Modules with preload (e.x. nodejs --experimental-modules -r main-es6.js cli-es6.js)
Piped ES6 modules (e.x. cat cli-es6.js | nodejs --experimental-modules)
Pipe+preload module (e.x. cat cli-es6.js | nodejs --experimental-modules -r main-es6.js)
In the browser (in which case, CLI is false because there is no process.argv)
In mixed browser+server environments (e.x. ElectronJS, in which case both inline scripts and all modules loaded via <script> tags are considered CLI)
The only case where is does not work is when you preload the top-level script (e.x. nodejs -r cli.js cli.js). This problem cannot be solved by piping (e.x. cat cli.js | nodejs -r cli.js) because that executes the script twice (once as a required module and once as top-level). I do not believe there is any possible fix for this because there is no way to know what the main script will be from inside a preloaded script.
† Theoretically, errors might be thrown from inside of a getter for an object (e.x. if someone were crazy enough to do Object.defineProperty(globalThis, "process", { get(){throw 0} });), however this will never happen under default circumstances for the properties used in the code snippet in any environment.
How can I detect whether my node.js file was called directly from console (windows and unix systems) or loaded using the ESM module import ( import {foo} from 'bar.js')
Such functionality is not exposed. For the moment you should separate your cli and library logic into separate files.
Answer from node.js core contributor devsnek replying to nodejs/help/issues/2420
It's the right answer in my point of view

Resources