Hỏi đáp

How do I get the path to the current script with Node.js?

How would I get the path to the script in Node.js?

I know there’s process.cwd, but that only refers to the directory where the script was called, not of the script itself. For instance, say I’m in /home/kyle/ and I run the following command:

node /home/kyle/some/dir/file.js

If I call process.cwd(), I get /home/kyle/, not /home/kyle/some/dir/. Is there a way to get that directory?

 Answers:

I found it after looking through the documentation again. What I was looking for were the __filename and __dirname module-level variables.

  • __filename is the file name of the current module. This is the resolved absolute path of the current module file. (ex:/home/kyle/some/dir/file.js)
  • __dirname is the directory name of the current module. (ex:/home/kyle/some/dir)

UPDATE: If your are working with ES Modules, i.e. if you are using "type":"module" in your package.json, starting with Node.js 20.11 / 21.2, you can use import.meta.dirname and import.meta.filename:

console.log(import.meta.filename);
console.log(import.meta.dirname);

Bài viết liên quan

Back to top button