Determine project root from a running node.js application












237














Is there a better way than process.cwd() to determine the root directory of a running node.js process? Something like the equivalent of Rails.root, but for Node.js. I'm looking for something that is as predictable and reliable as possible.










share|improve this question






















  • Any chance you could un-accept the accepted, wrong, answer?
    – Dave Newton
    Jul 23 '14 at 18:28






  • 7




    try process.env.PWD... see my answer below.
    – Alexander Mills
    May 26 '15 at 18:18


















237














Is there a better way than process.cwd() to determine the root directory of a running node.js process? Something like the equivalent of Rails.root, but for Node.js. I'm looking for something that is as predictable and reliable as possible.










share|improve this question






















  • Any chance you could un-accept the accepted, wrong, answer?
    – Dave Newton
    Jul 23 '14 at 18:28






  • 7




    try process.env.PWD... see my answer below.
    – Alexander Mills
    May 26 '15 at 18:18
















237












237








237


92





Is there a better way than process.cwd() to determine the root directory of a running node.js process? Something like the equivalent of Rails.root, but for Node.js. I'm looking for something that is as predictable and reliable as possible.










share|improve this question













Is there a better way than process.cwd() to determine the root directory of a running node.js process? Something like the equivalent of Rails.root, but for Node.js. I'm looking for something that is as predictable and reliable as possible.







node.js






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Apr 22 '12 at 6:39









MrEvil

2,80042533




2,80042533












  • Any chance you could un-accept the accepted, wrong, answer?
    – Dave Newton
    Jul 23 '14 at 18:28






  • 7




    try process.env.PWD... see my answer below.
    – Alexander Mills
    May 26 '15 at 18:18




















  • Any chance you could un-accept the accepted, wrong, answer?
    – Dave Newton
    Jul 23 '14 at 18:28






  • 7




    try process.env.PWD... see my answer below.
    – Alexander Mills
    May 26 '15 at 18:18


















Any chance you could un-accept the accepted, wrong, answer?
– Dave Newton
Jul 23 '14 at 18:28




Any chance you could un-accept the accepted, wrong, answer?
– Dave Newton
Jul 23 '14 at 18:28




7




7




try process.env.PWD... see my answer below.
– Alexander Mills
May 26 '15 at 18:18






try process.env.PWD... see my answer below.
– Alexander Mills
May 26 '15 at 18:18














22 Answers
22






active

oldest

votes


















475














There are several 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:



var path = require('path');
var appDir = path.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.



global.X



Node has a 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:



var appRoot = require('app-root-path');
var myModule = require(appRoot + '/lib/my-module.js');


The app-root-path module uses several different 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.






share|improve this answer



















  • 3




    require.main.filename did work for me. Thanks
    – ktkaushik
    Oct 3 '13 at 20:23






  • 1




    @Kevin in this case, mocha is the entry point of your application. This is just an example of why finding the "project root" is so difficult--it depends so much on the situation and what you mean by "project root."
    – inxilpro
    Apr 28 '14 at 19:37






  • 1




    @Kevin I completely understand. My point is just that the concept of "project root" is much easier for a human to understand than a computer. If you want a fool-proof method, you need to configure it. Using require.main.filename will work most of the time, but not all of the time.
    – inxilpro
    Apr 29 '14 at 18:08








  • 2




    Tangentially related: this is an incredibly clever way to organize your Node project so that you don't have to worry about this problem so much: allanhortle.com/2015/02/04/…
    – inxilpro
    Feb 5 '15 at 2:11






  • 8




    path.parse(process.mainModule.filename).dir
    – Cory Robinson
    Sep 14 '16 at 18:41



















45














__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.






share|improve this answer



















  • 2




    If used with caution, this could work pretty well. But it would give different results when doing bin/server.js vs cd bin && server.js. (assuming these js files are marked being executable)
    – Myrne Stol
    Jun 7 '13 at 16:21








  • 1




    Using process.cwd() has worked like a charm for me, even when running mocha tests. Thank you!
    – Diogo Schneider
    Mar 23 at 14:00



















42














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






share|improve this answer



















  • 21




    -1: To load the settings file you need a path, to then get reference path to that file? Not solving anything...
    – goliatone
    Aug 27 '13 at 18:33






  • 1




    @goliatone can you check my edit please :)
    – Fareed Alnamrouti
    Nov 22 '13 at 20:37






  • 2




    Upvoted for taking the time to review and edit. It still feels brittle, but that might just be because there is not a better way to achieve this
    – goliatone
    Nov 23 '13 at 4:48








  • 4




    Something users will want to keep in mind with this approach is that node_modules is often excluded from version control. So if you work with a team or ever need to clone your repository, you'll have to come up with another solution to keep that settings file in sync.
    – Travesty3
    Jul 7 '16 at 15:05










  • @Travesty3 the settings module is actually an empty module that is exporting the content of a file in the project root :P
    – Fareed Alnamrouti
    May 5 '17 at 9:58



















14














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






share|improve this answer



















  • 3




    This works great on (most) unix systems. As soon as you want your npm module/app to work on Windows, PWD is undefined and this fails.
    – Jeremy Wiebe
    Mar 2 '17 at 16:10










  • process.cwd()
    – Muhammad Umer
    Oct 5 at 19:51










  • @MuhammadUmer why would process.cwd() always be the same as project root?
    – Alexander Mills
    Oct 5 at 19:54










  • if you call it in root file then it'd be
    – Muhammad Umer
    Oct 5 at 20:30



















10














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!






share|improve this answer





























    6














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





    share|improve this answer































      6














      Maybe you can try traversing upwards from __filename until you find a package.json, and decide that's the main directory your current file belongs to.






      share|improve this answer





























        4














        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





        share|improve this answer































          2














          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.






          share|improve this answer





























            1














            I use this.



            For my module named mymodule



            var BASE_DIR = __dirname.replace(/^(.*/mymodule)(.*)$/, '$1')






            share|improve this answer





























              1














              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






              share|improve this answer





























                0














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





                share|improve this answer





























                  0














                  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.






                  share|improve this answer





























                    0














                    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.




                    1. Install the package: npm install sexy-require --save



                    2. Include require('sexy-require') once on the top of your main application file.



                      require('sexy-require');
                      const routers = require('/routers');
                      const api = require('$api');
                      ...



                    3. 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







                    share|improve this answer





























                      0














                      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.






                      share|improve this answer





























                        0














                        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.






                        share|improve this answer





























                          0














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





                          share|improve this answer





























                            0














                            As simple as add this line to your module in root, usually it is app.js



                            global.__basedir = __dirname;


                            Then _basedir will be accessiable to all your modules.






                            share|improve this answer





























                              -1














                              Try path._makeLong('some_filename_on_root.js');



                              example:



                              cons path = require('path');
                              console.log(path._makeLong('some_filename_on_root.js');


                              That will return full path from root of your node application (same position of package.json)






                              share|improve this answer





























                                -1














                                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...






                                share|improve this answer





























                                  -1














                                  Just use:



                                   path.resolve("./") ... output is your project root directory





                                  share|improve this answer





























                                    -2














                                    to get current file's pathname:


                                    define in that file:





                                    var get_stack = function() {
                                    var orig = Error.prepareStackTrace;
                                    Error.prepareStackTrace = function(_, stack) {
                                    return stack;
                                    };
                                    var err = new Error;
                                    Error.captureStackTrace(err, arguments.callee);
                                    var stack = err.stack;
                                    Error.prepareStackTrace = orig;
                                    return stack;
                                    };



                                    usage in that file:





                                    console.log(get_stack()[0].getFileName());



                                    API:
                                    StackTrace






                                    share|improve this answer





















                                      Your Answer






                                      StackExchange.ifUsing("editor", function () {
                                      StackExchange.using("externalEditor", function () {
                                      StackExchange.using("snippets", function () {
                                      StackExchange.snippets.init();
                                      });
                                      });
                                      }, "code-snippets");

                                      StackExchange.ready(function() {
                                      var channelOptions = {
                                      tags: "".split(" "),
                                      id: "1"
                                      };
                                      initTagRenderer("".split(" "), "".split(" "), channelOptions);

                                      StackExchange.using("externalEditor", function() {
                                      // Have to fire editor after snippets, if snippets enabled
                                      if (StackExchange.settings.snippets.snippetsEnabled) {
                                      StackExchange.using("snippets", function() {
                                      createEditor();
                                      });
                                      }
                                      else {
                                      createEditor();
                                      }
                                      });

                                      function createEditor() {
                                      StackExchange.prepareEditor({
                                      heartbeatType: 'answer',
                                      autoActivateHeartbeat: false,
                                      convertImagesToLinks: true,
                                      noModals: true,
                                      showLowRepImageUploadWarning: true,
                                      reputationToPostImages: 10,
                                      bindNavPrevention: true,
                                      postfix: "",
                                      imageUploader: {
                                      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                                      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                                      allowUrls: true
                                      },
                                      onDemand: true,
                                      discardSelector: ".discard-answer"
                                      ,immediatelyShowMarkdownHelp:true
                                      });


                                      }
                                      });














                                      draft saved

                                      draft discarded


















                                      StackExchange.ready(
                                      function () {
                                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f10265798%2fdetermine-project-root-from-a-running-node-js-application%23new-answer', 'question_page');
                                      }
                                      );

                                      Post as a guest















                                      Required, but never shown

























                                      22 Answers
                                      22






                                      active

                                      oldest

                                      votes








                                      22 Answers
                                      22






                                      active

                                      oldest

                                      votes









                                      active

                                      oldest

                                      votes






                                      active

                                      oldest

                                      votes









                                      475














                                      There are several 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:



                                      var path = require('path');
                                      var appDir = path.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.



                                      global.X



                                      Node has a 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:



                                      var appRoot = require('app-root-path');
                                      var myModule = require(appRoot + '/lib/my-module.js');


                                      The app-root-path module uses several different 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.






                                      share|improve this answer



















                                      • 3




                                        require.main.filename did work for me. Thanks
                                        – ktkaushik
                                        Oct 3 '13 at 20:23






                                      • 1




                                        @Kevin in this case, mocha is the entry point of your application. This is just an example of why finding the "project root" is so difficult--it depends so much on the situation and what you mean by "project root."
                                        – inxilpro
                                        Apr 28 '14 at 19:37






                                      • 1




                                        @Kevin I completely understand. My point is just that the concept of "project root" is much easier for a human to understand than a computer. If you want a fool-proof method, you need to configure it. Using require.main.filename will work most of the time, but not all of the time.
                                        – inxilpro
                                        Apr 29 '14 at 18:08








                                      • 2




                                        Tangentially related: this is an incredibly clever way to organize your Node project so that you don't have to worry about this problem so much: allanhortle.com/2015/02/04/…
                                        – inxilpro
                                        Feb 5 '15 at 2:11






                                      • 8




                                        path.parse(process.mainModule.filename).dir
                                        – Cory Robinson
                                        Sep 14 '16 at 18:41
















                                      475














                                      There are several 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:



                                      var path = require('path');
                                      var appDir = path.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.



                                      global.X



                                      Node has a 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:



                                      var appRoot = require('app-root-path');
                                      var myModule = require(appRoot + '/lib/my-module.js');


                                      The app-root-path module uses several different 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.






                                      share|improve this answer



















                                      • 3




                                        require.main.filename did work for me. Thanks
                                        – ktkaushik
                                        Oct 3 '13 at 20:23






                                      • 1




                                        @Kevin in this case, mocha is the entry point of your application. This is just an example of why finding the "project root" is so difficult--it depends so much on the situation and what you mean by "project root."
                                        – inxilpro
                                        Apr 28 '14 at 19:37






                                      • 1




                                        @Kevin I completely understand. My point is just that the concept of "project root" is much easier for a human to understand than a computer. If you want a fool-proof method, you need to configure it. Using require.main.filename will work most of the time, but not all of the time.
                                        – inxilpro
                                        Apr 29 '14 at 18:08








                                      • 2




                                        Tangentially related: this is an incredibly clever way to organize your Node project so that you don't have to worry about this problem so much: allanhortle.com/2015/02/04/…
                                        – inxilpro
                                        Feb 5 '15 at 2:11






                                      • 8




                                        path.parse(process.mainModule.filename).dir
                                        – Cory Robinson
                                        Sep 14 '16 at 18:41














                                      475












                                      475








                                      475






                                      There are several 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:



                                      var path = require('path');
                                      var appDir = path.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.



                                      global.X



                                      Node has a 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:



                                      var appRoot = require('app-root-path');
                                      var myModule = require(appRoot + '/lib/my-module.js');


                                      The app-root-path module uses several different 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.






                                      share|improve this answer














                                      There are several 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:



                                      var path = require('path');
                                      var appDir = path.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.



                                      global.X



                                      Node has a 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:



                                      var appRoot = require('app-root-path');
                                      var myModule = require(appRoot + '/lib/my-module.js');


                                      The app-root-path module uses several different 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.







                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited Apr 7 '16 at 3:46

























                                      answered Sep 10 '13 at 14:22









                                      inxilpro

                                      14.1k22024




                                      14.1k22024








                                      • 3




                                        require.main.filename did work for me. Thanks
                                        – ktkaushik
                                        Oct 3 '13 at 20:23






                                      • 1




                                        @Kevin in this case, mocha is the entry point of your application. This is just an example of why finding the "project root" is so difficult--it depends so much on the situation and what you mean by "project root."
                                        – inxilpro
                                        Apr 28 '14 at 19:37






                                      • 1




                                        @Kevin I completely understand. My point is just that the concept of "project root" is much easier for a human to understand than a computer. If you want a fool-proof method, you need to configure it. Using require.main.filename will work most of the time, but not all of the time.
                                        – inxilpro
                                        Apr 29 '14 at 18:08








                                      • 2




                                        Tangentially related: this is an incredibly clever way to organize your Node project so that you don't have to worry about this problem so much: allanhortle.com/2015/02/04/…
                                        – inxilpro
                                        Feb 5 '15 at 2:11






                                      • 8




                                        path.parse(process.mainModule.filename).dir
                                        – Cory Robinson
                                        Sep 14 '16 at 18:41














                                      • 3




                                        require.main.filename did work for me. Thanks
                                        – ktkaushik
                                        Oct 3 '13 at 20:23






                                      • 1




                                        @Kevin in this case, mocha is the entry point of your application. This is just an example of why finding the "project root" is so difficult--it depends so much on the situation and what you mean by "project root."
                                        – inxilpro
                                        Apr 28 '14 at 19:37






                                      • 1




                                        @Kevin I completely understand. My point is just that the concept of "project root" is much easier for a human to understand than a computer. If you want a fool-proof method, you need to configure it. Using require.main.filename will work most of the time, but not all of the time.
                                        – inxilpro
                                        Apr 29 '14 at 18:08








                                      • 2




                                        Tangentially related: this is an incredibly clever way to organize your Node project so that you don't have to worry about this problem so much: allanhortle.com/2015/02/04/…
                                        – inxilpro
                                        Feb 5 '15 at 2:11






                                      • 8




                                        path.parse(process.mainModule.filename).dir
                                        – Cory Robinson
                                        Sep 14 '16 at 18:41








                                      3




                                      3




                                      require.main.filename did work for me. Thanks
                                      – ktkaushik
                                      Oct 3 '13 at 20:23




                                      require.main.filename did work for me. Thanks
                                      – ktkaushik
                                      Oct 3 '13 at 20:23




                                      1




                                      1




                                      @Kevin in this case, mocha is the entry point of your application. This is just an example of why finding the "project root" is so difficult--it depends so much on the situation and what you mean by "project root."
                                      – inxilpro
                                      Apr 28 '14 at 19:37




                                      @Kevin in this case, mocha is the entry point of your application. This is just an example of why finding the "project root" is so difficult--it depends so much on the situation and what you mean by "project root."
                                      – inxilpro
                                      Apr 28 '14 at 19:37




                                      1




                                      1




                                      @Kevin I completely understand. My point is just that the concept of "project root" is much easier for a human to understand than a computer. If you want a fool-proof method, you need to configure it. Using require.main.filename will work most of the time, but not all of the time.
                                      – inxilpro
                                      Apr 29 '14 at 18:08






                                      @Kevin I completely understand. My point is just that the concept of "project root" is much easier for a human to understand than a computer. If you want a fool-proof method, you need to configure it. Using require.main.filename will work most of the time, but not all of the time.
                                      – inxilpro
                                      Apr 29 '14 at 18:08






                                      2




                                      2




                                      Tangentially related: this is an incredibly clever way to organize your Node project so that you don't have to worry about this problem so much: allanhortle.com/2015/02/04/…
                                      – inxilpro
                                      Feb 5 '15 at 2:11




                                      Tangentially related: this is an incredibly clever way to organize your Node project so that you don't have to worry about this problem so much: allanhortle.com/2015/02/04/…
                                      – inxilpro
                                      Feb 5 '15 at 2:11




                                      8




                                      8




                                      path.parse(process.mainModule.filename).dir
                                      – Cory Robinson
                                      Sep 14 '16 at 18:41




                                      path.parse(process.mainModule.filename).dir
                                      – Cory Robinson
                                      Sep 14 '16 at 18:41













                                      45














                                      __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.






                                      share|improve this answer



















                                      • 2




                                        If used with caution, this could work pretty well. But it would give different results when doing bin/server.js vs cd bin && server.js. (assuming these js files are marked being executable)
                                        – Myrne Stol
                                        Jun 7 '13 at 16:21








                                      • 1




                                        Using process.cwd() has worked like a charm for me, even when running mocha tests. Thank you!
                                        – Diogo Schneider
                                        Mar 23 at 14:00
















                                      45














                                      __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.






                                      share|improve this answer



















                                      • 2




                                        If used with caution, this could work pretty well. But it would give different results when doing bin/server.js vs cd bin && server.js. (assuming these js files are marked being executable)
                                        – Myrne Stol
                                        Jun 7 '13 at 16:21








                                      • 1




                                        Using process.cwd() has worked like a charm for me, even when running mocha tests. Thank you!
                                        – Diogo Schneider
                                        Mar 23 at 14:00














                                      45












                                      45








                                      45






                                      __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.






                                      share|improve this answer














                                      __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.







                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited Mar 30 '16 at 19:23









                                      pkyeck

                                      11.4k96186




                                      11.4k96186










                                      answered Jun 7 '13 at 15:45









                                      izb

                                      23.8k3097157




                                      23.8k3097157








                                      • 2




                                        If used with caution, this could work pretty well. But it would give different results when doing bin/server.js vs cd bin && server.js. (assuming these js files are marked being executable)
                                        – Myrne Stol
                                        Jun 7 '13 at 16:21








                                      • 1




                                        Using process.cwd() has worked like a charm for me, even when running mocha tests. Thank you!
                                        – Diogo Schneider
                                        Mar 23 at 14:00














                                      • 2




                                        If used with caution, this could work pretty well. But it would give different results when doing bin/server.js vs cd bin && server.js. (assuming these js files are marked being executable)
                                        – Myrne Stol
                                        Jun 7 '13 at 16:21








                                      • 1




                                        Using process.cwd() has worked like a charm for me, even when running mocha tests. Thank you!
                                        – Diogo Schneider
                                        Mar 23 at 14:00








                                      2




                                      2




                                      If used with caution, this could work pretty well. But it would give different results when doing bin/server.js vs cd bin && server.js. (assuming these js files are marked being executable)
                                      – Myrne Stol
                                      Jun 7 '13 at 16:21






                                      If used with caution, this could work pretty well. But it would give different results when doing bin/server.js vs cd bin && server.js. (assuming these js files are marked being executable)
                                      – Myrne Stol
                                      Jun 7 '13 at 16:21






                                      1




                                      1




                                      Using process.cwd() has worked like a charm for me, even when running mocha tests. Thank you!
                                      – Diogo Schneider
                                      Mar 23 at 14:00




                                      Using process.cwd() has worked like a charm for me, even when running mocha tests. Thank you!
                                      – Diogo Schneider
                                      Mar 23 at 14:00











                                      42














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






                                      share|improve this answer



















                                      • 21




                                        -1: To load the settings file you need a path, to then get reference path to that file? Not solving anything...
                                        – goliatone
                                        Aug 27 '13 at 18:33






                                      • 1




                                        @goliatone can you check my edit please :)
                                        – Fareed Alnamrouti
                                        Nov 22 '13 at 20:37






                                      • 2




                                        Upvoted for taking the time to review and edit. It still feels brittle, but that might just be because there is not a better way to achieve this
                                        – goliatone
                                        Nov 23 '13 at 4:48








                                      • 4




                                        Something users will want to keep in mind with this approach is that node_modules is often excluded from version control. So if you work with a team or ever need to clone your repository, you'll have to come up with another solution to keep that settings file in sync.
                                        – Travesty3
                                        Jul 7 '16 at 15:05










                                      • @Travesty3 the settings module is actually an empty module that is exporting the content of a file in the project root :P
                                        – Fareed Alnamrouti
                                        May 5 '17 at 9:58
















                                      42














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






                                      share|improve this answer



















                                      • 21




                                        -1: To load the settings file you need a path, to then get reference path to that file? Not solving anything...
                                        – goliatone
                                        Aug 27 '13 at 18:33






                                      • 1




                                        @goliatone can you check my edit please :)
                                        – Fareed Alnamrouti
                                        Nov 22 '13 at 20:37






                                      • 2




                                        Upvoted for taking the time to review and edit. It still feels brittle, but that might just be because there is not a better way to achieve this
                                        – goliatone
                                        Nov 23 '13 at 4:48








                                      • 4




                                        Something users will want to keep in mind with this approach is that node_modules is often excluded from version control. So if you work with a team or ever need to clone your repository, you'll have to come up with another solution to keep that settings file in sync.
                                        – Travesty3
                                        Jul 7 '16 at 15:05










                                      • @Travesty3 the settings module is actually an empty module that is exporting the content of a file in the project root :P
                                        – Fareed Alnamrouti
                                        May 5 '17 at 9:58














                                      42












                                      42








                                      42






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






                                      share|improve this answer














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







                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited Nov 22 '13 at 20:36

























                                      answered Aug 18 '13 at 23:20









                                      Fareed Alnamrouti

                                      19.7k26155




                                      19.7k26155








                                      • 21




                                        -1: To load the settings file you need a path, to then get reference path to that file? Not solving anything...
                                        – goliatone
                                        Aug 27 '13 at 18:33






                                      • 1




                                        @goliatone can you check my edit please :)
                                        – Fareed Alnamrouti
                                        Nov 22 '13 at 20:37






                                      • 2




                                        Upvoted for taking the time to review and edit. It still feels brittle, but that might just be because there is not a better way to achieve this
                                        – goliatone
                                        Nov 23 '13 at 4:48








                                      • 4




                                        Something users will want to keep in mind with this approach is that node_modules is often excluded from version control. So if you work with a team or ever need to clone your repository, you'll have to come up with another solution to keep that settings file in sync.
                                        – Travesty3
                                        Jul 7 '16 at 15:05










                                      • @Travesty3 the settings module is actually an empty module that is exporting the content of a file in the project root :P
                                        – Fareed Alnamrouti
                                        May 5 '17 at 9:58














                                      • 21




                                        -1: To load the settings file you need a path, to then get reference path to that file? Not solving anything...
                                        – goliatone
                                        Aug 27 '13 at 18:33






                                      • 1




                                        @goliatone can you check my edit please :)
                                        – Fareed Alnamrouti
                                        Nov 22 '13 at 20:37






                                      • 2




                                        Upvoted for taking the time to review and edit. It still feels brittle, but that might just be because there is not a better way to achieve this
                                        – goliatone
                                        Nov 23 '13 at 4:48








                                      • 4




                                        Something users will want to keep in mind with this approach is that node_modules is often excluded from version control. So if you work with a team or ever need to clone your repository, you'll have to come up with another solution to keep that settings file in sync.
                                        – Travesty3
                                        Jul 7 '16 at 15:05










                                      • @Travesty3 the settings module is actually an empty module that is exporting the content of a file in the project root :P
                                        – Fareed Alnamrouti
                                        May 5 '17 at 9:58








                                      21




                                      21




                                      -1: To load the settings file you need a path, to then get reference path to that file? Not solving anything...
                                      – goliatone
                                      Aug 27 '13 at 18:33




                                      -1: To load the settings file you need a path, to then get reference path to that file? Not solving anything...
                                      – goliatone
                                      Aug 27 '13 at 18:33




                                      1




                                      1




                                      @goliatone can you check my edit please :)
                                      – Fareed Alnamrouti
                                      Nov 22 '13 at 20:37




                                      @goliatone can you check my edit please :)
                                      – Fareed Alnamrouti
                                      Nov 22 '13 at 20:37




                                      2




                                      2




                                      Upvoted for taking the time to review and edit. It still feels brittle, but that might just be because there is not a better way to achieve this
                                      – goliatone
                                      Nov 23 '13 at 4:48






                                      Upvoted for taking the time to review and edit. It still feels brittle, but that might just be because there is not a better way to achieve this
                                      – goliatone
                                      Nov 23 '13 at 4:48






                                      4




                                      4




                                      Something users will want to keep in mind with this approach is that node_modules is often excluded from version control. So if you work with a team or ever need to clone your repository, you'll have to come up with another solution to keep that settings file in sync.
                                      – Travesty3
                                      Jul 7 '16 at 15:05




                                      Something users will want to keep in mind with this approach is that node_modules is often excluded from version control. So if you work with a team or ever need to clone your repository, you'll have to come up with another solution to keep that settings file in sync.
                                      – Travesty3
                                      Jul 7 '16 at 15:05












                                      @Travesty3 the settings module is actually an empty module that is exporting the content of a file in the project root :P
                                      – Fareed Alnamrouti
                                      May 5 '17 at 9:58




                                      @Travesty3 the settings module is actually an empty module that is exporting the content of a file in the project root :P
                                      – Fareed Alnamrouti
                                      May 5 '17 at 9:58











                                      14














                                      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






                                      share|improve this answer



















                                      • 3




                                        This works great on (most) unix systems. As soon as you want your npm module/app to work on Windows, PWD is undefined and this fails.
                                        – Jeremy Wiebe
                                        Mar 2 '17 at 16:10










                                      • process.cwd()
                                        – Muhammad Umer
                                        Oct 5 at 19:51










                                      • @MuhammadUmer why would process.cwd() always be the same as project root?
                                        – Alexander Mills
                                        Oct 5 at 19:54










                                      • if you call it in root file then it'd be
                                        – Muhammad Umer
                                        Oct 5 at 20:30
















                                      14














                                      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






                                      share|improve this answer



















                                      • 3




                                        This works great on (most) unix systems. As soon as you want your npm module/app to work on Windows, PWD is undefined and this fails.
                                        – Jeremy Wiebe
                                        Mar 2 '17 at 16:10










                                      • process.cwd()
                                        – Muhammad Umer
                                        Oct 5 at 19:51










                                      • @MuhammadUmer why would process.cwd() always be the same as project root?
                                        – Alexander Mills
                                        Oct 5 at 19:54










                                      • if you call it in root file then it'd be
                                        – Muhammad Umer
                                        Oct 5 at 20:30














                                      14












                                      14








                                      14






                                      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






                                      share|improve this answer














                                      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







                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited Nov 8 '15 at 4:39

























                                      answered May 26 '15 at 18:14









                                      Alexander Mills

                                      17.9k31150301




                                      17.9k31150301








                                      • 3




                                        This works great on (most) unix systems. As soon as you want your npm module/app to work on Windows, PWD is undefined and this fails.
                                        – Jeremy Wiebe
                                        Mar 2 '17 at 16:10










                                      • process.cwd()
                                        – Muhammad Umer
                                        Oct 5 at 19:51










                                      • @MuhammadUmer why would process.cwd() always be the same as project root?
                                        – Alexander Mills
                                        Oct 5 at 19:54










                                      • if you call it in root file then it'd be
                                        – Muhammad Umer
                                        Oct 5 at 20:30














                                      • 3




                                        This works great on (most) unix systems. As soon as you want your npm module/app to work on Windows, PWD is undefined and this fails.
                                        – Jeremy Wiebe
                                        Mar 2 '17 at 16:10










                                      • process.cwd()
                                        – Muhammad Umer
                                        Oct 5 at 19:51










                                      • @MuhammadUmer why would process.cwd() always be the same as project root?
                                        – Alexander Mills
                                        Oct 5 at 19:54










                                      • if you call it in root file then it'd be
                                        – Muhammad Umer
                                        Oct 5 at 20:30








                                      3




                                      3




                                      This works great on (most) unix systems. As soon as you want your npm module/app to work on Windows, PWD is undefined and this fails.
                                      – Jeremy Wiebe
                                      Mar 2 '17 at 16:10




                                      This works great on (most) unix systems. As soon as you want your npm module/app to work on Windows, PWD is undefined and this fails.
                                      – Jeremy Wiebe
                                      Mar 2 '17 at 16:10












                                      process.cwd()
                                      – Muhammad Umer
                                      Oct 5 at 19:51




                                      process.cwd()
                                      – Muhammad Umer
                                      Oct 5 at 19:51












                                      @MuhammadUmer why would process.cwd() always be the same as project root?
                                      – Alexander Mills
                                      Oct 5 at 19:54




                                      @MuhammadUmer why would process.cwd() always be the same as project root?
                                      – Alexander Mills
                                      Oct 5 at 19:54












                                      if you call it in root file then it'd be
                                      – Muhammad Umer
                                      Oct 5 at 20:30




                                      if you call it in root file then it'd be
                                      – Muhammad Umer
                                      Oct 5 at 20:30











                                      10














                                      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!






                                      share|improve this answer


























                                        10














                                        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!






                                        share|improve this answer
























                                          10












                                          10








                                          10






                                          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!






                                          share|improve this answer












                                          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!







                                          share|improve this answer












                                          share|improve this answer



                                          share|improve this answer










                                          answered May 14 '17 at 6:08









                                          Patrick

                                          30936




                                          30936























                                              6














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





                                              share|improve this answer




























                                                6














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





                                                share|improve this answer


























                                                  6












                                                  6








                                                  6






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





                                                  share|improve this answer














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






                                                  share|improve this answer














                                                  share|improve this answer



                                                  share|improve this answer








                                                  edited Jan 9 '15 at 21:18









                                                  Paul DelRe

                                                  3,49011824




                                                  3,49011824










                                                  answered Apr 18 '14 at 13:10









                                                  Konstantin Isaev

                                                  486712




                                                  486712























                                                      6














                                                      Maybe you can try traversing upwards from __filename until you find a package.json, and decide that's the main directory your current file belongs to.






                                                      share|improve this answer


























                                                        6














                                                        Maybe you can try traversing upwards from __filename until you find a package.json, and decide that's the main directory your current file belongs to.






                                                        share|improve this answer
























                                                          6












                                                          6








                                                          6






                                                          Maybe you can try traversing upwards from __filename until you find a package.json, and decide that's the main directory your current file belongs to.






                                                          share|improve this answer












                                                          Maybe you can try traversing upwards from __filename until you find a package.json, and decide that's the main directory your current file belongs to.







                                                          share|improve this answer












                                                          share|improve this answer



                                                          share|improve this answer










                                                          answered Jun 19 '15 at 16:04









                                                          kvz

                                                          3,2102623




                                                          3,2102623























                                                              4














                                                              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





                                                              share|improve this answer




























                                                                4














                                                                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





                                                                share|improve this answer


























                                                                  4












                                                                  4








                                                                  4






                                                                  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





                                                                  share|improve this answer














                                                                  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






                                                                  share|improve this answer














                                                                  share|improve this answer



                                                                  share|improve this answer








                                                                  edited Nov 12 at 7:59









                                                                  Ilyas karim

                                                                  1,19411625




                                                                  1,19411625










                                                                  answered Feb 5 '17 at 11:17









                                                                  Avi Tshuva

                                                                  1359




                                                                  1359























                                                                      2














                                                                      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.






                                                                      share|improve this answer


























                                                                        2














                                                                        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.






                                                                        share|improve this answer
























                                                                          2












                                                                          2








                                                                          2






                                                                          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.






                                                                          share|improve this answer












                                                                          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.







                                                                          share|improve this answer












                                                                          share|improve this answer



                                                                          share|improve this answer










                                                                          answered Aug 10 '15 at 10:51









                                                                          Ben Davies

                                                                          32148




                                                                          32148























                                                                              1














                                                                              I use this.



                                                                              For my module named mymodule



                                                                              var BASE_DIR = __dirname.replace(/^(.*/mymodule)(.*)$/, '$1')






                                                                              share|improve this answer


























                                                                                1














                                                                                I use this.



                                                                                For my module named mymodule



                                                                                var BASE_DIR = __dirname.replace(/^(.*/mymodule)(.*)$/, '$1')






                                                                                share|improve this answer
























                                                                                  1












                                                                                  1








                                                                                  1






                                                                                  I use this.



                                                                                  For my module named mymodule



                                                                                  var BASE_DIR = __dirname.replace(/^(.*/mymodule)(.*)$/, '$1')






                                                                                  share|improve this answer












                                                                                  I use this.



                                                                                  For my module named mymodule



                                                                                  var BASE_DIR = __dirname.replace(/^(.*/mymodule)(.*)$/, '$1')







                                                                                  share|improve this answer












                                                                                  share|improve this answer



                                                                                  share|improve this answer










                                                                                  answered Dec 2 '16 at 15:08









                                                                                  vbranden

                                                                                  2,9001210




                                                                                  2,9001210























                                                                                      1














                                                                                      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






                                                                                      share|improve this answer


























                                                                                        1














                                                                                        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






                                                                                        share|improve this answer
























                                                                                          1












                                                                                          1








                                                                                          1






                                                                                          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






                                                                                          share|improve this answer












                                                                                          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







                                                                                          share|improve this answer












                                                                                          share|improve this answer



                                                                                          share|improve this answer










                                                                                          answered Nov 30 at 11:39









                                                                                          VIKAS KOHLI

                                                                                          1,9841224




                                                                                          1,9841224























                                                                                              0














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





                                                                                              share|improve this answer


























                                                                                                0














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





                                                                                                share|improve this answer
























                                                                                                  0












                                                                                                  0








                                                                                                  0






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





                                                                                                  share|improve this answer












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






                                                                                                  share|improve this answer












                                                                                                  share|improve this answer



                                                                                                  share|improve this answer










                                                                                                  answered Mar 1 '15 at 4:59









                                                                                                  Karthik M

                                                                                                  23213




                                                                                                  23213























                                                                                                      0














                                                                                                      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.






                                                                                                      share|improve this answer


























                                                                                                        0














                                                                                                        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.






                                                                                                        share|improve this answer
























                                                                                                          0












                                                                                                          0








                                                                                                          0






                                                                                                          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.






                                                                                                          share|improve this answer












                                                                                                          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.







                                                                                                          share|improve this answer












                                                                                                          share|improve this answer



                                                                                                          share|improve this answer










                                                                                                          answered May 28 '16 at 6:58









                                                                                                          Dariusz Sikorski

                                                                                                          2,2261633




                                                                                                          2,2261633























                                                                                                              0














                                                                                                              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.




                                                                                                              1. Install the package: npm install sexy-require --save



                                                                                                              2. Include require('sexy-require') once on the top of your main application file.



                                                                                                                require('sexy-require');
                                                                                                                const routers = require('/routers');
                                                                                                                const api = require('$api');
                                                                                                                ...



                                                                                                              3. 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







                                                                                                              share|improve this answer


























                                                                                                                0














                                                                                                                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.




                                                                                                                1. Install the package: npm install sexy-require --save



                                                                                                                2. Include require('sexy-require') once on the top of your main application file.



                                                                                                                  require('sexy-require');
                                                                                                                  const routers = require('/routers');
                                                                                                                  const api = require('$api');
                                                                                                                  ...



                                                                                                                3. 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







                                                                                                                share|improve this answer
























                                                                                                                  0












                                                                                                                  0








                                                                                                                  0






                                                                                                                  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.




                                                                                                                  1. Install the package: npm install sexy-require --save



                                                                                                                  2. Include require('sexy-require') once on the top of your main application file.



                                                                                                                    require('sexy-require');
                                                                                                                    const routers = require('/routers');
                                                                                                                    const api = require('$api');
                                                                                                                    ...



                                                                                                                  3. 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







                                                                                                                  share|improve this answer












                                                                                                                  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.




                                                                                                                  1. Install the package: npm install sexy-require --save



                                                                                                                  2. Include require('sexy-require') once on the top of your main application file.



                                                                                                                    require('sexy-require');
                                                                                                                    const routers = require('/routers');
                                                                                                                    const api = require('$api');
                                                                                                                    ...



                                                                                                                  3. 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








                                                                                                                  share|improve this answer












                                                                                                                  share|improve this answer



                                                                                                                  share|improve this answer










                                                                                                                  answered Jan 12 at 17:50









                                                                                                                  sultan

                                                                                                                  802712




                                                                                                                  802712























                                                                                                                      0














                                                                                                                      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.






                                                                                                                      share|improve this answer


























                                                                                                                        0














                                                                                                                        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.






                                                                                                                        share|improve this answer
























                                                                                                                          0












                                                                                                                          0








                                                                                                                          0






                                                                                                                          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.






                                                                                                                          share|improve this answer












                                                                                                                          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.







                                                                                                                          share|improve this answer












                                                                                                                          share|improve this answer



                                                                                                                          share|improve this answer










                                                                                                                          answered Mar 18 at 0:59









                                                                                                                          Andre Figueiredo

                                                                                                                          7,12643260




                                                                                                                          7,12643260























                                                                                                                              0














                                                                                                                              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.






                                                                                                                              share|improve this answer


























                                                                                                                                0














                                                                                                                                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.






                                                                                                                                share|improve this answer
























                                                                                                                                  0












                                                                                                                                  0








                                                                                                                                  0






                                                                                                                                  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.






                                                                                                                                  share|improve this answer












                                                                                                                                  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.







                                                                                                                                  share|improve this answer












                                                                                                                                  share|improve this answer



                                                                                                                                  share|improve this answer










                                                                                                                                  answered Jun 24 at 10:15









                                                                                                                                  Pulkit Aggarwal

                                                                                                                                  96811120




                                                                                                                                  96811120























                                                                                                                                      0














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





                                                                                                                                      share|improve this answer


























                                                                                                                                        0














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





                                                                                                                                        share|improve this answer
























                                                                                                                                          0












                                                                                                                                          0








                                                                                                                                          0






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





                                                                                                                                          share|improve this answer












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






                                                                                                                                          share|improve this answer












                                                                                                                                          share|improve this answer



                                                                                                                                          share|improve this answer










                                                                                                                                          answered Sep 27 at 3:07









                                                                                                                                          Codebeat

                                                                                                                                          4,18953972




                                                                                                                                          4,18953972























                                                                                                                                              0














                                                                                                                                              As simple as add this line to your module in root, usually it is app.js



                                                                                                                                              global.__basedir = __dirname;


                                                                                                                                              Then _basedir will be accessiable to all your modules.






                                                                                                                                              share|improve this answer


























                                                                                                                                                0














                                                                                                                                                As simple as add this line to your module in root, usually it is app.js



                                                                                                                                                global.__basedir = __dirname;


                                                                                                                                                Then _basedir will be accessiable to all your modules.






                                                                                                                                                share|improve this answer
























                                                                                                                                                  0












                                                                                                                                                  0








                                                                                                                                                  0






                                                                                                                                                  As simple as add this line to your module in root, usually it is app.js



                                                                                                                                                  global.__basedir = __dirname;


                                                                                                                                                  Then _basedir will be accessiable to all your modules.






                                                                                                                                                  share|improve this answer












                                                                                                                                                  As simple as add this line to your module in root, usually it is app.js



                                                                                                                                                  global.__basedir = __dirname;


                                                                                                                                                  Then _basedir will be accessiable to all your modules.







                                                                                                                                                  share|improve this answer












                                                                                                                                                  share|improve this answer



                                                                                                                                                  share|improve this answer










                                                                                                                                                  answered Dec 15 at 12:16









                                                                                                                                                  didxga

                                                                                                                                                  3,80943348




                                                                                                                                                  3,80943348























                                                                                                                                                      -1














                                                                                                                                                      Try path._makeLong('some_filename_on_root.js');



                                                                                                                                                      example:



                                                                                                                                                      cons path = require('path');
                                                                                                                                                      console.log(path._makeLong('some_filename_on_root.js');


                                                                                                                                                      That will return full path from root of your node application (same position of package.json)






                                                                                                                                                      share|improve this answer


























                                                                                                                                                        -1














                                                                                                                                                        Try path._makeLong('some_filename_on_root.js');



                                                                                                                                                        example:



                                                                                                                                                        cons path = require('path');
                                                                                                                                                        console.log(path._makeLong('some_filename_on_root.js');


                                                                                                                                                        That will return full path from root of your node application (same position of package.json)






                                                                                                                                                        share|improve this answer
























                                                                                                                                                          -1












                                                                                                                                                          -1








                                                                                                                                                          -1






                                                                                                                                                          Try path._makeLong('some_filename_on_root.js');



                                                                                                                                                          example:



                                                                                                                                                          cons path = require('path');
                                                                                                                                                          console.log(path._makeLong('some_filename_on_root.js');


                                                                                                                                                          That will return full path from root of your node application (same position of package.json)






                                                                                                                                                          share|improve this answer












                                                                                                                                                          Try path._makeLong('some_filename_on_root.js');



                                                                                                                                                          example:



                                                                                                                                                          cons path = require('path');
                                                                                                                                                          console.log(path._makeLong('some_filename_on_root.js');


                                                                                                                                                          That will return full path from root of your node application (same position of package.json)







                                                                                                                                                          share|improve this answer












                                                                                                                                                          share|improve this answer



                                                                                                                                                          share|improve this answer










                                                                                                                                                          answered Jun 28 '16 at 18:38









                                                                                                                                                          The-x Laws

                                                                                                                                                          6111




                                                                                                                                                          6111























                                                                                                                                                              -1














                                                                                                                                                              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...






                                                                                                                                                              share|improve this answer


























                                                                                                                                                                -1














                                                                                                                                                                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...






                                                                                                                                                                share|improve this answer
























                                                                                                                                                                  -1












                                                                                                                                                                  -1








                                                                                                                                                                  -1






                                                                                                                                                                  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...






                                                                                                                                                                  share|improve this answer












                                                                                                                                                                  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...







                                                                                                                                                                  share|improve this answer












                                                                                                                                                                  share|improve this answer



                                                                                                                                                                  share|improve this answer










                                                                                                                                                                  answered Oct 5 at 8:11









                                                                                                                                                                  Pankaj Shinde

                                                                                                                                                                  525719




                                                                                                                                                                  525719























                                                                                                                                                                      -1














                                                                                                                                                                      Just use:



                                                                                                                                                                       path.resolve("./") ... output is your project root directory





                                                                                                                                                                      share|improve this answer


























                                                                                                                                                                        -1














                                                                                                                                                                        Just use:



                                                                                                                                                                         path.resolve("./") ... output is your project root directory





                                                                                                                                                                        share|improve this answer
























                                                                                                                                                                          -1












                                                                                                                                                                          -1








                                                                                                                                                                          -1






                                                                                                                                                                          Just use:



                                                                                                                                                                           path.resolve("./") ... output is your project root directory





                                                                                                                                                                          share|improve this answer












                                                                                                                                                                          Just use:



                                                                                                                                                                           path.resolve("./") ... output is your project root directory






                                                                                                                                                                          share|improve this answer












                                                                                                                                                                          share|improve this answer



                                                                                                                                                                          share|improve this answer










                                                                                                                                                                          answered Oct 10 at 9:34









                                                                                                                                                                          aligatorr89

                                                                                                                                                                          11




                                                                                                                                                                          11























                                                                                                                                                                              -2














                                                                                                                                                                              to get current file's pathname:


                                                                                                                                                                              define in that file:





                                                                                                                                                                              var get_stack = function() {
                                                                                                                                                                              var orig = Error.prepareStackTrace;
                                                                                                                                                                              Error.prepareStackTrace = function(_, stack) {
                                                                                                                                                                              return stack;
                                                                                                                                                                              };
                                                                                                                                                                              var err = new Error;
                                                                                                                                                                              Error.captureStackTrace(err, arguments.callee);
                                                                                                                                                                              var stack = err.stack;
                                                                                                                                                                              Error.prepareStackTrace = orig;
                                                                                                                                                                              return stack;
                                                                                                                                                                              };



                                                                                                                                                                              usage in that file:





                                                                                                                                                                              console.log(get_stack()[0].getFileName());



                                                                                                                                                                              API:
                                                                                                                                                                              StackTrace






                                                                                                                                                                              share|improve this answer


























                                                                                                                                                                                -2














                                                                                                                                                                                to get current file's pathname:


                                                                                                                                                                                define in that file:





                                                                                                                                                                                var get_stack = function() {
                                                                                                                                                                                var orig = Error.prepareStackTrace;
                                                                                                                                                                                Error.prepareStackTrace = function(_, stack) {
                                                                                                                                                                                return stack;
                                                                                                                                                                                };
                                                                                                                                                                                var err = new Error;
                                                                                                                                                                                Error.captureStackTrace(err, arguments.callee);
                                                                                                                                                                                var stack = err.stack;
                                                                                                                                                                                Error.prepareStackTrace = orig;
                                                                                                                                                                                return stack;
                                                                                                                                                                                };



                                                                                                                                                                                usage in that file:





                                                                                                                                                                                console.log(get_stack()[0].getFileName());



                                                                                                                                                                                API:
                                                                                                                                                                                StackTrace






                                                                                                                                                                                share|improve this answer
























                                                                                                                                                                                  -2












                                                                                                                                                                                  -2








                                                                                                                                                                                  -2






                                                                                                                                                                                  to get current file's pathname:


                                                                                                                                                                                  define in that file:





                                                                                                                                                                                  var get_stack = function() {
                                                                                                                                                                                  var orig = Error.prepareStackTrace;
                                                                                                                                                                                  Error.prepareStackTrace = function(_, stack) {
                                                                                                                                                                                  return stack;
                                                                                                                                                                                  };
                                                                                                                                                                                  var err = new Error;
                                                                                                                                                                                  Error.captureStackTrace(err, arguments.callee);
                                                                                                                                                                                  var stack = err.stack;
                                                                                                                                                                                  Error.prepareStackTrace = orig;
                                                                                                                                                                                  return stack;
                                                                                                                                                                                  };



                                                                                                                                                                                  usage in that file:





                                                                                                                                                                                  console.log(get_stack()[0].getFileName());



                                                                                                                                                                                  API:
                                                                                                                                                                                  StackTrace






                                                                                                                                                                                  share|improve this answer












                                                                                                                                                                                  to get current file's pathname:


                                                                                                                                                                                  define in that file:





                                                                                                                                                                                  var get_stack = function() {
                                                                                                                                                                                  var orig = Error.prepareStackTrace;
                                                                                                                                                                                  Error.prepareStackTrace = function(_, stack) {
                                                                                                                                                                                  return stack;
                                                                                                                                                                                  };
                                                                                                                                                                                  var err = new Error;
                                                                                                                                                                                  Error.captureStackTrace(err, arguments.callee);
                                                                                                                                                                                  var stack = err.stack;
                                                                                                                                                                                  Error.prepareStackTrace = orig;
                                                                                                                                                                                  return stack;
                                                                                                                                                                                  };



                                                                                                                                                                                  usage in that file:





                                                                                                                                                                                  console.log(get_stack()[0].getFileName());



                                                                                                                                                                                  API:
                                                                                                                                                                                  StackTrace







                                                                                                                                                                                  share|improve this answer












                                                                                                                                                                                  share|improve this answer



                                                                                                                                                                                  share|improve this answer










                                                                                                                                                                                  answered Oct 8 '15 at 3:58









                                                                                                                                                                                  user1012316

                                                                                                                                                                                  573




                                                                                                                                                                                  573






























                                                                                                                                                                                      draft saved

                                                                                                                                                                                      draft discarded




















































                                                                                                                                                                                      Thanks for contributing an answer to Stack Overflow!


                                                                                                                                                                                      • Please be sure to answer the question. Provide details and share your research!

                                                                                                                                                                                      But avoid



                                                                                                                                                                                      • Asking for help, clarification, or responding to other answers.

                                                                                                                                                                                      • Making statements based on opinion; back them up with references or personal experience.


                                                                                                                                                                                      To learn more, see our tips on writing great answers.





                                                                                                                                                                                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                                                                                                                                                                      Please pay close attention to the following guidance:


                                                                                                                                                                                      • Please be sure to answer the question. Provide details and share your research!

                                                                                                                                                                                      But avoid



                                                                                                                                                                                      • Asking for help, clarification, or responding to other answers.

                                                                                                                                                                                      • Making statements based on opinion; back them up with references or personal experience.


                                                                                                                                                                                      To learn more, see our tips on writing great answers.




                                                                                                                                                                                      draft saved


                                                                                                                                                                                      draft discarded














                                                                                                                                                                                      StackExchange.ready(
                                                                                                                                                                                      function () {
                                                                                                                                                                                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f10265798%2fdetermine-project-root-from-a-running-node-js-application%23new-answer', 'question_page');
                                                                                                                                                                                      }
                                                                                                                                                                                      );

                                                                                                                                                                                      Post as a guest















                                                                                                                                                                                      Required, but never shown





















































                                                                                                                                                                                      Required, but never shown














                                                                                                                                                                                      Required, but never shown












                                                                                                                                                                                      Required, but never shown







                                                                                                                                                                                      Required, but never shown

































                                                                                                                                                                                      Required, but never shown














                                                                                                                                                                                      Required, but never shown












                                                                                                                                                                                      Required, but never shown







                                                                                                                                                                                      Required, but never shown







                                                                                                                                                                                      Popular posts from this blog

                                                                                                                                                                                      What visual should I use to simply compare current year value vs last year in Power BI desktop

                                                                                                                                                                                      Alexandru Averescu

                                                                                                                                                                                      Trompette piccolo