Skip to content

Instantly share code, notes, and snippets.

@shhider
Last active November 21, 2022 08:13
Show Gist options
  • Save shhider/a35c7be2e68379945fe815c460545f14 to your computer and use it in GitHub Desktop.
Save shhider/a35c7be2e68379945fe815c460545f14 to your computer and use it in GitHub Desktop.
[paths in Node.js] #nodejs #path #__dirname #__filename
// https://stackoverflow.com/a/62892482/3676413
import { fileURLToPath } from 'url';
import { dirname } from 'path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
  • __dirname: 获得当前执行文件所在目录的完整目录名;
  • __filename: 获得当前执行文件的带有完整绝对路径的文件名;
  • process.cwd():获得当前执行 node 命令时候的文件夹目录名;
  • ./: 不使用require时候,./process.cwd()一样;使用require时候,与__dirname一样。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment