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

vfh0ocws  于 2023-04-20  发布在  其他
关注(0)|答案(1)|浏览(129)

我正在尝试使用fs.mkdirSync从**/API/sendEmail.js**创建临时文件

fs.mkdirSync(path.join(__dirname, "../../public"));

但是在Vercel(部署平台)上,所有文件夹都是只读的,我不能创建任何临时文件。
错误:
“errorMessage”:“EROFS:只读文件系统,mkdir '/var/task/.next/server/public'”
我看到有一些关于这方面的问题,但还不清楚,你们中有谁做到了吗?

lnlaulya

lnlaulya1#

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)
    }
  }
}

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

相关问题