osgsm.io
HomeNotesNode.js の ES modules で __dirname や __filename を使う

Node.js の ES modules で __dirname や __filename を使う

Published Mar 12, 2025
Updated Mar 17, 2025

CommonJS では、__filename__dirname 変数をよく使う。それぞれ現在のファイルのフルパス、現在のファイルがあるディレクトリを表す。

しかし、ES modules ではそれらが使えない。

Node.js v21.2.0 からはそれらの代わりとして import.meta.dirname, import.meta.filename が使える。

21.2.0 or later
const __dirname = import.meta.dirname;
const __filename = import.meta.filename;

それより前の Node.js では node:url モジュールの fileURLToPath()import.meta.url を渡して __filename を取得する。

その __filenamenode:path モジュールの dirname() に渡すことで __dirname を取得できる。

earlier than 21.2.0
import { fileURLToPath } from "node:url";
import path from "node:path";
 
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

import.meta.url は、該当のモジュールの file: URL を表す。これを fileURLToPath() に渡してパスに変換している。

path.dirname() はパス文字列を受け取り、そのパスのディレクトリ名を返す。


参考