Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

App base path from a module in NodeJS

I'm building a web app in NodeJS, 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 app 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 under Windows so there is no process.env.PWD and I don't want to be platform specific anyway.

like image 204
Clint Powell Avatar asked Feb 07 '14 20:02

Clint Powell


People also ask

How do I find the base path in node JS?

You can use process. cwd() which returns the current working directory of the process. That command works fine if you execute your node application from the base application directory. However, if you execute your node application from different directory, say, its parent directory (e.g. node yourapp\index.

What is __ Basedir?

__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'); I know what you're thinking: oh no a global!

What is path module in node JS?

Node. js provides you with the path module that allows you to interact with file paths easily. The path module has many useful properties and methods to access and manipulate paths in the file system. The path is a core module in Node.

What is __ Dirname in node?

__dirname: It is a local variable that returns the directory name of the current module. It returns the folder path of the current JavaScript file. Difference between process.cwd() vs __dirname in Node.js is as follows: process.cwd()


1 Answers

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 application from the base application directory. However, if you execute your node application from different directory, say, its parent directory (e.g. node yourapp\index.js) then __dirname mechanism will work much better.

I hope that will help.

like image 159
Tom Avatar answered Oct 01 '22 20:10

Tom