如何获取Google App Engine中部署应用的根目录?
获取已部署应用根路径的实用方案
如果部署环境没提供根路径的环境变量,直接通过代码动态推导是更可靠的方式,以下是几种主流开发场景的实现方法:
Node.js 项目
利用内置的__dirname和path模块来获取:const path = require('path'); // 入口文件在项目根目录时直接用 const rootPath = path.resolve(__dirname); // 入口文件在子目录(比如src/index.js)时,向上追溯一级 const rootPath = path.resolve(__dirname, '../');若使用ES模块,
__dirname不可用,可替换为import.meta.url:import { fileURLToPath } from 'url'; import { dirname, resolve } from 'path'; const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); const rootPath = resolve(__dirname, '../');Python 项目
通过os模块获取当前脚本的绝对路径,再推导根目录:import os # 获取当前脚本所在目录的绝对路径 current_dir = os.path.dirname(os.path.abspath(__file__)) # 当前脚本在子目录时,多套一层dirname追溯到根路径 root_path = os.path.dirname(current_dir)Java Web 应用
可以通过类加载器获取项目资源根路径:// 获取WEB-INF目录路径,再向上推导根目录 String webInfPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); String rootPath = new File(webInfPath).getParent();或者直接获取当前工作目录:
String rootPath = new File("").getAbsolutePath();
核心思路就是从当前执行的代码文件路径出发,向上追溯到项目根目录,这种方式不依赖环境变量,适配绝大多数部署场景,比依赖平台提供的环境变量更靠谱。
内容的提问来源于stack exchange,提问作者MarcS82
相关产品推荐
相关产品推荐

