【问题标题】:ENOENT: no such file or directory, open '/var/task/google-cloud-key.json' VercelENOENT:没有这样的文件或目录,打开 '/var/task/google-cloud-key.json' Vercel
【发布时间】:2021-10-21 17:46:22
【问题描述】:

请帮我解决..

我的JS file 文件位于Next JS app > pages/api/profile 中,google-cloud-key.json 位于 Next JS 应用程序根文件夹本身,其中 package.json 就在那里。

在本地一切正常,但低于 Vercel 给出的错误

ENOENT: no such file or directory, open '/var/task/google-cloud-key.json' vercel

我的 google-cloud-key.json 在下一个 JS 应用的根目录下。

我也试过下面的代码:

const storage = new Storage({
            projectId: 'careful-relic-319511',
            keyFilename: __dirname + '/../../../google-cloud-key.json'
        });

现在出现以下错误:

ENOENT: no such file or directory, open '/var/task/.next/server/google-cloud-key.json'] {\n  errno: -2,\n  code: 'ENOENT',\n  syscall: 'open',\n  path: '/var/task/.next/server/google-cloud-key.json'\n}\nEND

【问题讨论】:

  • 你可以像const data = await import('../data.json')一样正常导入JSON。
  • 尝试using process.cwd() 而不是__dirname

标签: javascript node.js reactjs next.js vercel


【解决方案1】:

嘿,我找到了一个很好的解决方案

  1. Base64 对 json 文件进行编码。 (https://www.base64encode.org/)

  2. 设置一个环境变量(在本地和vercel设置中)这个编码字符串。 (在我的例子中是 GCP_CRED_FILE)

const gcsKey = JSON.parse(
  Buffer.from(process.env.GCP_CRED_FILE, 'base64').toString()
);

const storage = new Storage({
  credentials: {
    client_email: gcsKey.client_email,
    private_key: gcsKey.private_key
  },
  projectId: gcsKey.project_id
});

这对我有用。使用 nextjs 11 和 vercel 部署测试

此外,您不需要将文件存储或推送到存储库或存储它(这可能是安全威胁)

【讨论】:

    猜你喜欢
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 2022-10-18
    • 1970-01-01
    • 2020-08-05
    • 1970-01-01
    • 1970-01-01
    • 2019-07-05
    相关资源
    最近更新 更多