3

I am currently trying to create a temp file from /api/sendEmail.js with fs.mkdirSync

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

but on Vercel (deployment platform) all folders are read-only and I can't create any temp files.

Error:

"errorMessage": "EROFS: read-only file system, mkdir '/var/task/.next/server/public'"

I have seen there are some questions about this but it's not clear, have any of you guys managed to do this?

3
  • Aside from the permission problems, you should not use synchronous filesystem access on your server ... Commented Oct 9, 2021 at 12:45
  • You'll have to use an external file storage provider if you want to create/delete files at runtime. Commented Oct 9, 2021 at 13:05
  • i saw that on vercel we can store and delete files in tmp folder but i can't find any examples or documentation Commented Oct 9, 2021 at 13:35

1 Answer 1

8

Vercel allows creation of files in /tmp directory. However, there are limitations with this. https://github.com/vercel/vercel/discussions/5320

An example of /api function that writes and reads files is:


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

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.