ノードのマニュアルを見ると、 でファイルのディレクトリを取得できることがわかります__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
。
require、exports、module.exports、__filename、__dirname はありません
これらの CommonJS 変数は ES モジュールでは使用できません。
require
ESモジュールにインポートするには、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