You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vercel服务端无法读取public目录下文件问题求助

问题:Vercel部署后无法读取HTML邮件模板文件(本地运行正常)

使用nodemailer发送邮件时,本地环境能正常读取public目录下的HTML模板文件,但部署到Vercel服务端后,出现文件找不到的错误。

代码示例

const orderConfirmationTemplatePathForUser = "/public/mailTemplates/orderConfirmationTemplate.html";

const sourceForUser = (await fs.readFile(process.cwd() + orderConfirmationTemplatePathForUser, 'utf8')).toString();

文件夹结构(src与public同级)

/src
/public
--/mailTemplates
----/orderConfirmationTemplate.html

Vercel上的错误信息

[Error: ENOENT: no such file or directory, open '/var/task/public/mailTemplates/orderConfirmationTemplate.html'] {
  errno: -2,
  code: 'ENOENT',
  syscall: 'open',
  path: '/var/task/public/mailTemplates/orderConfirmationTemplate.html'
}

解决方案

  • Vercel构建后的目录结构和本地不同,public目录不会被直接放到/var/task下,不能依赖process.cwd()拼接路径。改用path模块结合__dirname计算正确的文件路径:
    const path = require('path');
    // 根据代码所在位置调整相对路径,示例假设代码在src目录下的文件中
    const templatePath = path.join(__dirname, '../../public/mailTemplates/orderConfirmationTemplate.html');
    const sourceForUser = await fs.readFile(templatePath, 'utf8');
    
  • 直接将HTML模板内容作为字符串写入代码,或使用模板引擎预编译模板,彻底绕开文件读取问题。
  • 检查Vercel部署配置,确保模板文件被包含在部署包中:比如在package.json的files字段添加public/mailTemplates/,或在vercel.json中配置静态资源规则。

内容的提问来源于stack exchange,提问作者Rishabh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 04:27:20