Get the current folder in Node

Two ways to refer to the file system: ./ and __dirname, which illustrate

There are basically two ways to reference the current folder in a Node.js script:

  • ./
  • __dirname

along with./, Have../, It points to the parent folder. They behave in the same way.

There is a big difference between the two.

use__dirnameThe path of the folder will be returned in the Node scriptThe location of the current JavaScript file.

use./Will give youCurrent working directory. It will return the same result as callingprocess.cwd().

Initially, the current working directory is the path of the folder where you run the node command, but you can change the path by using the following command during the execution of the script:process.chdir()API.

Only one place./Refers to the current file path, which is located inrequire()call. over there,./(For convenience) The JavaScript file path will always be referenced, allowing you to import other modules based on the folder structure.

Download mine for freeNode.js manual

More node tutorials: