__dirname がノード REPL で定義されていないのはなぜですか? 質問する

__dirname がノード REPL で定義されていないのはなぜですか? 質問する

ノードのマニュアルを見ると、 でファイルのディレクトリを取得できることがわかります__dirnameが、REPL ではこれは未定義のようです。これは私の誤解でしょうか、それともどこにエラーがあるのでしょうか?

$ node
> console.log(__dirname)
ReferenceError: __dirname is not defined
    at repl:1:14
    at REPLServer.eval (repl.js:80:21)
    at Interface.<anonymous> (repl.js:182:12)
    at Interface.emit (events.js:67:17)
    at Interface._onLine (readline.js:162:10)
    at Interface._line (readline.js:426:8)
    at Interface._ttyWrite (readline.js:603:14)
    at ReadStream.<anonymous> (readline.js:82:12)
    at ReadStream.emit (events.js:88:20)
    at ReadStream._emitKey (tty.js:320:10)

ベストアンサー1

使用している場合Node.js モジュール、存在しませ__dirname__filename

からNode.js ドキュメント:

require、exports、module.exports、__filename、__dirname はありません

これらの CommonJS 変数は ES モジュールでは使用できません。

requireESモジュールにインポートするには、module.createRequire()

および に相当するものは__filename__dirname各ファイル内で次のように作成できます。import.meta.url:

import { fileURLToPath } from 'url';
import { dirname } from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

https://nodejs.org/docs/latest-v15.x/api/esm.html#esm_no_filename_or_dirname

おすすめ記事