Why is __dirname not defined in node REPL?

后端 未结 11 1364
傲寒
傲寒 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:16

    In ES6 use:

    import path from 'path';
    const __dirname = path.resolve();
    

    also available when node is called with --experimental-modules

    0 讨论(0)
  • 2020-12-12 15:18

    Seems like you could also do this:

    __dirname=fs.realpathSync('.');
    

    of course, dont forget fs=require('fs')

    (it's not really global in node scripts exactly, its just defined on the module level)

    0 讨论(0)
  • 2020-12-12 15:23

    Building on the existing answers here, you could define this in your REPL:

    __dirname = path.resolve(path.dirname(''));
    

    Or:

    __dirname = path.resolve();
    

    If no path segments are passed, path.resolve() will return the absolute path of the current working directory.


    Or @Jthorpe's alternatives:

    __dirname = process.cwd();
    __dirname = fs.realpathSync('.');
    __dirname = process.env.PWD
    
    0 讨论(0)
  • 2020-12-12 15:23

    sometimes we make a file with .js extension and add consol.log(_dirname); but we face errors, we are in a hurry, so we forget to add one more underscore before the "dirname" so we face reference error.correct syntax is consol.log(__dirname);

    0 讨论(0)
  • 2020-12-12 15:26

    I was also trying to join my path using path.join(__dirname, 'access.log') but it was throwing the same error.

    Here is how I fixed it:

    I first imported the path package and declared a variable named __dirname, then called the resolve path method.

    In CommonJS

    var path = require("path");
    
    var __dirname = path.resolve();
    

    In ES6+

    import path  from 'path';
    
    const __dirname = path.resolve();
    

    Happy coding.......

    0 讨论(0)
提交回复
热议问题