如何在 NextJS 中从 /api 创建文件?

Ste*_*vić 2 next.js vercel

我目前正在尝试从/api/sendEmail.js创建一个临时文件fs.mkdirSync

fs.mkdirSync(path.join(__dirname, "../../public"));
Run Code Online (Sandbox Code Playgroud)

但在 Vercel(部署平台)上,所有文件夹都是只读的,我无法创建任何临时文件。

错误:

"errorMessage": "EROFS: 只读文件系统,mkdir '/var/task/.next/server/public'"

我看到有一些关于此的问题,但不清楚,你们有人设法做到这一点吗?

小智 6

Vercel 允许在目录中创建文件/tmp。然而,这样做也有局限性。https://github.com/vercel/vercel/discussions/5320

/api写入和读取文件的函数示例是:


import fs from 'fs';

export default async function handler(req, res) {
    const {
      method,
      body,
    } = req

    try {
      switch (method) {
        case 'GET': {
// read
          // This line opens the file as a readable stream
          const readStream = fs.createReadStream('/tmp/text.txt')

          // This will wait until we know the readable stream is actually valid before piping
          readStream.on('open', function () {
            // This just pipes the read stream to the response object (which goes to the client)
            readStream.pipe(res)
          })

          // This catches any errors that happen while creating the readable stream (usually invalid names)
          readStream.on('error', function (err) {
            res.end(err)
          })
          return
        }
        case 'POST':
          // write
          fs.writeFileSync('./test.txt', JSON.stringify(body))
          break
        default:
          res.setHeader('Allow', ['GET', 'POST'])
          res.status(405).end(`Method ${method} Not Allowed`)
      }
      // send result
      return res.status(200).json({ message: 'Success' })
    } catch (error) {
      return res.status(500).json(error)
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

另请参阅:https ://vercel.com/support/articles/how-can-i-use-files-in-serverless-functions