NodeJS

The difference between the methods or attributes used to represent paths, such as __dirname , __filename , etc. in NodeJS

  • __dirname The absolute path of the current file, which will not change with the directory where the command is executed
  • __filename The absolute path of the current file, which will not change with the directory where the command is executed
  • module.filename The absolute path of the current file, which will not change with the directory where the command is executed
  • The working directory path of process.cwd() running the current script will change with the directory when executing the script
  • process.chdir() changes the working directory

For example, there is a project named test under /home/wsl :

 test└── parent └── child └── app.js

The content of the app.js file is as follows:

 console.log(__dirname)console.log(__filename)console.log(module.filename)console.log(module.filename === __filename)console.log(process.cwd())process.chdir('/home/wsl')console.log(process.cwd())

Then execute node parent/child/app.js in the test directory, and the output is as follows:

 /home/wsl/test/parent/child/home/wsl/test/parent/child/app.js/home/wsl/test/parent/child/app.jstrue/home/wsl/test/home/wsl

This article is reprinted from https://www.wujingquan.com/posts/9d5ee47d.html
This site is for inclusion only, and the copyright belongs to the original author.

Leave a Comment

Your email address will not be published.