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.
Top comments (0)