Firebase Cloud Functions部署后无法定位静态文件的问题求助
我刚接触Firebase Cloud Functions,想写个URL重写的功能,但死活搞不清楚部署后我的文件存在哪里。
模拟器用着不太顺手,所以我都是本地改完代码再部署,靠日志排查问题,但文件位置完全摸不着头脑。
我的函数代码是这样的:
const app = express(); app.use(express.static(path.join(__dirname, "..", "dist", "assets"))); exports.jambudipaApp = functions.https.onRequest((req, res) => { functions.logger.info(`__dirname = ${__dirname}`); const folders1 = fs.readdirSync(path.join(__dirname, "..")); functions.logger.info(`Folders in ${path.join(__dirname, "..")}: ${folders1}`); const folders2 = fs.readdirSync(__dirname); functions.logger.info(`Folders in ${__dirname}: ${folders2}`); if (req.headers.host === "<subdomain, handled elsewhere>") { return app(req, res); } else { res.sendFile(path.join(__dirname, "..", "dist", "public", "index.html")); } });
(折腾一天了,代码有点乱,见谅)
本地生成的文件都在dist目录里,是用Vite打包出来的。我的firebase.json配置如下:
{ "hosting": { "public": "dist", "ignore": [ "firebase.json", "**/.*", "**/node_modules/**" ] } }
这个配置在没用到Cloud Functions的其他项目里是正常的,所以我确定文件应该是被正确上传了,但上面的日志在Log Explorer里输出的结果是:
__dirname = /workspace
Folders in /: bin,boot,cloudsql,cnb,config,dev,dev,etc,home,layers,lib,lib64,media,mnt,opt,proc,proc,root,run,sbin,serve,srv,start,sys,sys,tmp,tmp,usr,var,workspace,www-data-home
Folders in /workspace: .gitignore,.googlebuild,.runtimeconfig.json,index.js,node_modules,package-lock.json,package.json
不管是/还是/workspace里都没有dist和public目录,这到底是怎么回事?
更新情况
我都懵了:
我改成了这样的代码:
functions.logger.info(`Requesting index.html from ${path.join(__dirname, "public", "index.html")}`); res.sendFile(path.join(__dirname, "public", "index.html"));
结果报错:
Error: ENOENT: no such file or directory, stat '/workspace/public/index.html'
但我直接访问https://example.com/public/index.html是能正常打开的,所以我肯定是路径写错了。
到底该怎么正确获取我的文件存储目录啊?
直接访问https://example.com/public/index.html没问题,但访问https://example.com就不行。我试过用path.join()和path.resolve(),后者会触发Firebase错误,前者直接404。
备注:内容来源于stack exchange,提问作者serlingpa

