Why is __dirname not defined in node REPL?

后端 未结 11 1361
傲寒
傲寒 2020-12-12 14:23

From the node manual I see that I can get the directory of a file with __dirname, but from the REPL this seems to be undefined. Is this a misunderstanding on my

11条回答
  •  时光说笑
    2020-12-12 15:10

    If you are using Node.js modules, __dirname and __filename don't exist.

    From the Node.js documentation:

    No require, exports, module.exports, __filename, __dirname

    These CommonJS variables are not available in ES modules.

    require can be imported into an ES module using module.createRequire().

    Equivalents of __filename and __dirname can be created inside of each file via import.meta.url:

    import { fileURLToPath } from 'url';
    import { dirname } from 'path';
    
    const __filename = fileURLToPath(import.meta.url);
    const __dirname = dirname(__filename);
    

    https://nodejs.org/api/esm.html#esm_no_require_exports_module_exports_filename_dirname

提交回复
热议问题