node.js 节点 __dirname 未定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8817423/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:59:53  来源:igfitidea点击:

node __dirname not defined

node.js

提问by topskip

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 side or where is the error?

从节点手册中我看到我可以使用 获取文件的目录__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)

回答by qiao

__dirnameis only defined in scripts. It's not available in REPL.

__dirname仅在脚本中定义。它在 REPL 中不可用。

try make a script a.js

尝试编写脚本 a.js

console.log(__dirname);

and run it:

并运行它:

node a.js

you will see __dirnameprinted.

你会看到__dirname打印出来的。

Added background explanation: __dirnamemeans 'The directory of this script'. In REPL, you don't have a script. Hence, __dirnamewould not have any real meaning.

添加了背景说明:__dirname表示“此脚本的目录”。在 REPL 中,您没有脚本。因此,__dirname不会有任何实际意义。

回答by c24w

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

基于此处现有的答案,您可以在 REPL 中定义它:

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

Or:

或者:

__dirname = path.resolve();

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

如果没有path传递段,path.resolve()将返回当前工作目录的绝对路径。



Or @Jthorpe's alternatives:

或@Jthorpe 的替代方案:

__dirname = process.cwd();
__dirname = fs.realpathSync('.');
__dirname = process.env.PWD

回答by t-reksio

In ES6 use:

在 ES6 中使用:

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

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

当节点被调用时也可用 --experimental-modules

回答by jeremywoertink

As @qiao said, you can't use __dirnamein the node repl. However, if you need need this value in the console, you can use path.resolve()or path.dirname(). Although, path.dirname()will just give you a "." so, probably not that helpful. Be sure to require('path').

正如@qiao 所说,您不能__dirname在节点 repl 中使用。但是,如果您需要在控制台中使用此值,则可以使用path.resolve()path.dirname()。虽然,path.dirname()只会给你一个“。” 所以,可能没有那么有帮助。一定要require('path')

回答by Desire Kaleba

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

我也试图加入我的路径,path.join(__dirname, 'access.log')但它抛出了同样的错误。

Here is how I fixed it:

这是我修复它的方法:

I first imported the pathpackage and declared a variable named __dirname, then called the resolvepathmethod.

我首先导入了路径包并声明了一个名为 的变量__dirname,然后调用了resolve路径方法。

In CommonJS

在 CommonJS 中

var path = require("path");

var __dirname = path.resolve();

In ES6+

在 ES6+ 中

import path  from 'path';

const __dirname = path.resolve();

Happy coding.......

快乐编码......

回答by Joel M Ward

Seems like you could also do this:

好像你也可以这样做:

__dirname=fs.realpathSync('.');

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

当然,不要忘记 fs=require('fs')

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

(它在节点脚本中并不是真正全局的,它只是在模块级别定义的)

回答by Siva Prakash

Though its not the solution to this problem I would like to add it as it may help others.

虽然它不是这个问题的解决方案,但我想添加它,因为它可能会帮助其他人。

You should have two underscoresbefore dirname, not one undersore(__dirnamenot _dirname).

你应该在 dirname 之前有两个下划线而不是一个 undersore( __dirnamenot _dirname)。

NodeJS Docs

NodeJS 文档

回答by Pawel

I was running a script from batch file as SYSTEM user and all variables like process.cwd(), path.resolve()and all other methods would give me path to C:\Windows\System32 folder instead of actual path. During experiments I noticed that when an error is thrown the stack contains a true path to the node file.

我正在以 SYSTEM 用户和所有变量(如 )的身份从批处理文件运行脚本process.cwd()path.resolve()所有其他方法都会为我提供 C:\Windows\System32 文件夹的路径,而不是实际路径。在实验期间,我注意到当抛出错误时,堆栈包含节点文件的真实路径。

Here's a very hacky way to get true path by triggering an error and extracting path from e.stack. Do not use.

这是通过触发错误并从 e.stack 中提取路径来获得真实路径的一种非常hacky 的方法。不使用。

// this should be the name of currently executed file
const currentFilename = 'index.js';

function veryHackyGetFolder() {
  try {
    throw new Error();
  } catch(e) {
    const fullMsg = e.stack.toString();
    const beginning = fullMsg.indexOf('file:///') + 8;
    const end = fullMsg.indexOf('\/' + currentFilename);
    const dir = fullMsg.substr(beginning, end - beginning).replace(/\//g, '\');
    return dir;
  }
}

Usage

用法

const dir = veryHackyGetFolder();

回答by vikky singh

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);

有时我们创建一个扩展名为 .js 的文件并添加 consol.log(_dirname); 但是我们遇到了错误,我们很着急,所以我们忘记在“dirname”之前再添加一个下划线,因此我们面临引用错误。正确的语法是consol.log(__dirname);