DEV Community

Zak Miller
Zak Miller

Posted on • Originally published at zakmiller.com

1

Google Cloud Functions and the File System

#go

If you want to write a cloud function, and you need to write temporary data to the file system, how do you do it?

Using /tmp. Under the hood, it's actually just storing it in memory but if you must simulate reading and writing to the file system it'll work.

I was cloning a repo programmatically and parsing JSON files from that repo, so it made sense for my situation.

To write:

func write() error {
    text := "Hello World"
    filepath := "/tmp/file"
    fmt.Printf("writing file %v\n", filepath)
    b := []byte(text)
    err := ioutil.WriteFile(filepath, b, 0644)
    switch  {
    case err != nil:
        fmt.Printf("error encountered writing file %v, %v\n", filepath, err)
        return err
    default:
        fmt.Printf("file wrote successfully\n")
        return nil
    }
}

To read:

func read() (string, error) {
    filepath := "tmp/file"
    fmt.Printf("reading file %v\n", filepath)
    content, err := ioutil.ReadFile(filepath)

    switch {
    case err != nil:
        fmt.Printf("error encountered reading file %v, %v\n", filepath, err)
        return "", err
    default:
        fmt.Printf("file %v read, content: %v\n", filepath, string(content))
        return string(content), nil
    }
}

You can find a complete sample here.

If you care about preserving the files you're writing, then don't use this solution. Instead, use something like this.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay