Câu hỏi phỏng vấn Nodejs
Câu hỏi

What's the difference between process.cwd() vs __dirname ?

Câu trả lời

In Node.js, process.cwd() and __dirname are both used to determine directory paths, but they serve different purposes and behave differently based on the context of the Node.js process and the module being executed.

process.cwd()

process.cwd() is a method of the global process object in Node.js that returns the current working directory of the process. This directory is the one from which the Node.js process was initiated. The value returned by process.cwd() can change if the current directory is modified during the execution of the process (e.g., by using process.chdir()). It is not tied to the location of the file where it is called, but rather to the execution context of the Node.js process[1][2][5][6].

__dirname

On the other hand, __dirname is a local variable available within each module in Node.js that represents the directory name of the path to the current module (JavaScript file). This means __dirname is always the directory in which the current JavaScript file resides. Unlike process.cwd(), __dirname does not change regardless of where the script was initiated from—it is always set to the directory of the file in which it is used[2][3][4][5][6].

Key Differences

  • Scope and Consistency: __dirname is consistent and local to the module, providing the path to the directory containing the current file. process.cwd(), however, can vary and reflects the process's current working directory, which can be different from the location of the fil...
junior

junior

Gợi ý câu hỏi phỏng vấn

middle

Are you familiar with differences between Node.js modules and ES6 modules?

middle

What is the meaning of the @ prefix on npm package?

expert

How V8 compiles JavaScript code?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào