ReasonJun

Node.js : __dirname / __filename / process.cwd() 본문

Backend/Node.js

Node.js : __dirname / __filename / process.cwd()

ReasonJun 2023. 6. 17. 14:41
728x90

 

In Node.js, the following three variables are used to get the current working directory and the filename of the current module:

  • __dirname
  • __filename
  • process.cwd()

__dirname is a special variable that is defined within each module. It returns the directory name of the current module, which is the directory that contains the current JavaScript file. For example, if the current file is /home/user/my_app/index.js, then __dirname will be /home/user/my_app.

 

__filename is another special variable that is defined within each module. It returns the filename of the current module, including the extension. For example, if the current file is /home/user/my_app/index.js, then __filename will be index.js.

 

process.cwd() is a method of the global process object. It returns the current working directory of the Node.js process. The current working directory is the directory that the Node.js process was started from.

 

The main difference between __dirname and process.cwd() is that __dirname is specific to the current module, while process.cwd() is global. This means that __dirname will always return the directory name of the current module, even if the module is loaded from a different directory. However, process.cwd() will return the current working directory of the Node.js process, which may be different from the directory that the current module is located in.

 

Here is an example of how to use __dirname and process.cwd() in Node.js:

const dirname = __dirname;
const filename = __filename;
const cwd = process.cwd();

console.log("__dirname:", dirname);
console.log("__filename:", filename);
console.log("process.cwd():", cwd);

This code will print the following output:

__dirname: /home/user/my_app
__filename: index.js
process.cwd(): /home/user

As you can see, __dirname is /home/user/my_app, __filename is index.js, and process.cwd() is /home/user. This is because the current module is index.js, which is located in the /home/user/my_app directory. The Node.js process was also started from the /home/user directory.

 

 

 

https://inpa.tistory.com/entry/NODE-%F0%9F%93%9A-dirname-filename-processcwd-%EC%B0%A8%EC%9D%B4-%EC%A0%95%EB%A6%AC

 

[NODE] 📚 __dirname / __filename / process.cwd() 차이 정리

__dirname 와 __filename 노드에서는 모듈 관계가 있는 경우가 많아 현재 파일의 경로나 파일명을 알아야 하는 경우가 많다. 노드는 __filename, __dirname 이라는 키워드로 경로에 대한 정보롤 제공한다. 파

inpa.tistory.com

 

__dirname / __filename / process.cwd()

728x90

'Backend > Node.js' 카테고리의 다른 글

Node.js : Blocking / non-Blocking  (0) 2023.09.03
Node.js : bindings  (0) 2023.09.02
In Node.js, the relationship between V8 and libuv  (0) 2023.09.02
Node.js : libuv concept  (0) 2023.09.02
Node.js : Concept and Features  (0) 2023.09.02
Comments