来自 NodeJS 模块的应用程序基本路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21637099/
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 16:49:26  来源:igfitidea点击:

App base path from a module in NodeJS

node.jsmodulepathfs

提问by Clint Powell

I'm building a web app in NodeJS, and I'm implementing my API routes in separate modules. In one of my routes I'm doing some file manipulation and I need to know the base app path. if I use __dirnameit gives me the directory that houses my module of course.

我正在 NodeJS 中构建一个 Web 应用程序,并且我正在单独的模块中实现我的 API 路由。在我的一条路线中,我正在进行一些文件操作,我需要知道基本应用程序路径。如果我使用__dirname它,当然会给我包含我的模块的目录。

I'm currently using this to get the base app path (given that I know the relative path to the module from base path):

我目前正在使用它来获取基本应用程序路径(假设我知道从基本路径到模块的相对路径):

path.join(__dirname, "../../", myfilename)

Is there a better way than using ../../? I'm running Node under Windows so there is no process.env.PWDand I don't want to be platform specific anyway.

有没有比使用更好的方法../../?我在 Windows 下运行 Node,所以没有process.env.PWD,我也不想成为特定于平台的。

采纳答案by Tom

The approach of using __dirnameis the most reliable one. It will always give you correct directory. You do not have to worry about ../../in Windows environment as path.join()will take care of that.

使用方法__dirname是最可靠的一种。它总是会给你正确的目录。您不必担心../../在 Windows 环境中path.join()会照顾到这一点。

There is an alternative solution though. You can use process.cwd()which returns the current working directory of the process. That command works fine if you execute your node application from the base application directory. However, if you execute your node application from different directory, say, its parent directory (e.g. node yourapp\index.js)then __dirnamemechanism will work much better.

不过有一个替代解决方案。您可以使用process.cwd()which 返回进程的当前工作目录。如果您从基本应用程序目录执行节点应用程序,那么该命令可以正常工作。然而,如果你从不同的目录执行你的节点应用程序,比如说,它的父目录(例如,node yourapp\index.js)那么__dirname机制会工作得更好。

I hope that will help.

我希望这会有所帮助。

回答by Samuli Asmala

You can use path.resolve()without arguments to get the working directory which is usually the base app path. If the argument is relative path then it's assumed to be relative to the current working directory so you can write

您可以使用不带参数的path.resolve()来获取工作目录,该目录通常是基本应用程序路径。如果参数是相对路径,则假定它是相对于当前工作目录的,因此您可以编写

require(path.resolve(myfilename));

to require your module at app root.

要求您的模块位于应用程序根目录。

回答by Hayreddin Tüzel

You can define a global variable like in your app.js:

您可以像在 app.js 中一样定义一个全局变量:

global.__basedir = __dirname;

Then you can use this global variable anywhere. Like that:

然后你可以在任何地方使用这个全局变量。像那样:

var base_path = __basedir