Reference · Files and processes

write_file

signature
write_file(str, any) -> null | error(str)

What it does

Writes a value as text to a file under the program's folder, replacing what was there, and makes the folders on the way. The value is written as print would show it: a string as it is, a number as its digits, a map or a list in Quillo's notation (for JSON, pass json.stringify(v)). It gives null when the file is written and an error value when it cannot be.

Examples

print(write_file("notes/today.txt", "milk\neggs"))print(read_file("notes/today.txt"))print(write_file("out/report.json", json.stringify({ total: 3 })))print(read_file("out/report.json"))
output
nullmilkeggsnull{"total":3}

Edge cases

print(write_file("a/b/c/d.txt", "deep"), read_file("a/b/c/d.txt"))print(write_file("x.txt", "first"), write_file("x.txt", "second"), read_file("x.txt"))print(write_file("n.txt", 42), read_file("n.txt"))print(write_file("m.txt", { a: 1, b: [1, 2] }), read_file("m.txt"))print(write_file("e.txt", null), len(read_file("e.txt")))print(write_file("../x.txt", "x"), write_file("", "x"))print(write_file(".ENV", "ADMIN=1"))print(write_file("MAIN.QWE", "x"), write_file("main.qwe.", "x"))
output
null deepnull null secondnull 42null { a: 1, b: [1, 2] }null 4err("write_file: path must stay inside the program's folder: ../x.txt") err("write_file: path must stay inside the program's folder: ")err("write_file: will not write .ENV: it is the program's settings (.env)")err("write_file: will not write MAIN.QWE: it is one of the program's own files") err("write_file: will not write main.qwe.: it is one of the program's own files")

Errors

A path that leaves the folder, one of the program's own files, or a file the system refuses to write, is an error value; ? passes it on. A path that is not a string is a runtime error.

let r = write_file("/tmp/x.txt", "x")print(is_err(r), r.error)
output
true write_file: path must stay inside the program's folder: /tmp/x.txt
this one fails
print(write_file(42, "x"))
output
line 1: `write_file` expects a str as argument 1, got int

Chaining

The path comes first in a pipeline, so the text is given in the call:

print("c.txt" | write_file("see"), "c.txt" | read_file)print(["a.txt", "b.txt"] | map((p) => write_file(p, upper(p))), read_file("a.txt"))
output
null see[null, null] A.TXT

See also

read_file, delete_file, json.stringify, save_upload

Thread
8Useful? Like it, or add to its thread below.

Thread 0 posts

On write_file(): questions, tips, corrections, and code that uses it.

No posts yet. The first one opens the thread.

    Edit this page on GitHub · every example's output was made by running it (tools/refcheck.mjs) · questions on Discord or r/quillo