Writing to temporary storage in a Google Cloud Function using Node JS

Here’s a quick example on how to do this.

/**
 * Responds to any HTTP request.
 *
 * @param {!express:Request} req HTTP request context.
 * @param {!express:Response} res HTTP response context.
 */

let os = require('os')
let fs = require('fs')

exports.helloWorld = (req, res) => {
  fs.writeFileSync(os.tmpdir()+'/test.txt','hello world','utf8');
  let read = fs.readFileSync(os.tmpdir()+'/test.txt','utf8'); // /tmp/test.txt
  res.status(200).send(read);
};

I recently had to store an intermediary response before shipping the data off to another resource (API to BigQuery) and wanted to take advantage of BigQuery’s free loading versus streaming.

From the Google docs,

“The only writeable part of the filesystem is the /tmp directory, which you can use to store temporary files in a function instance. This is a local disk mount point known as a “tmpfs” volume in which data written to the volume is stored in memory. Note that it will consume memory resources provisioned for the function.

The rest of the file system is read-only and accessible to the function.”

https://cloud.google.com/functions/docs/concepts/exec#file_system

Max memory right now is 2048mb so you’ll have to keep it under that assuming you’ve provisioned your function with that much memory.

Hope it helps someone!

Scroll to Top