How can I get the application base path from a module in Node.js?

module, node.js, node.js-fs, path

Solution

The approach of using `__dirname` is the most reliable one. It will always give you correct directory. You do not have to worry about `../../` in Windows environment as `path.join()` will take care of that.

There is an alternative solution though. You can use `process.cwd()` which returns the current working directory of the process. That command works fine if you execute your Node.js application from the base application directory. However, if you execute your Node.js application from different directory, say, its parent directory (e.g., `node yourapp\index.js)` then the `__dirname` mechanism will work much better.

Problem

I'm building a web application in Node.js, and I'm implementing my API routes in separate modules. In one of my routes I'm doing some file manipulation and I need to know the base app path. If I use `__dirname`, it gives me the directory that houses my module of course. I'm currently using this to get the base application path (given that I know the relative path to the module from base path): ``` path.join(__dirname, "../../", myfilename) ``` Is there a better way than using `../../`? I'm running Node.js under Windows, so there isn't any `process.env.PWD`, and I don't want to be platform-specific anyway.

Original source