Writing Files in Bnlang
The io module mirrors its read API on the write side:
io.write_file(path, data)— synchronous; overwrites the file.io.write_file_async(path, data, cb)— asynchronous; callback fires when the write is durable.io.append_file(path, data)— synchronous append (creates the file if missing).io.open_write(path)— streaming; push chunks one at a time.
Synchronous Write
The simplest form. Blocks until the bytes are on disk.
import "io" as io;
io.write_file("greeting.txt", "Hello from Bnlang!");
print("written");
Asynchronous Write
Returns immediately. The callback fires with an error argument (null on success) once the data is durable.
import "io" as io;
io.write_file_async("greeting.txt", "Hello, async!", function (err) {
if (err != null) {
print("write failed:", err);
return;
}
print("written");
});
print("scheduled");
Appending
For log files and accumulating output, use io.append_file — it doesn't truncate, and creates the file if needed.
import "io" as io;
io.append_file("app.log", "started up\n");
io.append_file("app.log", "ready\n");
Streaming Large Outputs
When the output doesn't fit in memory (or you don't want to buffer it), open a write stream and push chunks.
Don't forget to close() the stream — that's what flushes the final bytes to disk.
import "io" as io;
var sink = io.open_write("report.csv");
sink.write("id,name\n", function (err) { /* ... */ });
sink.write("1,Alice\n", function (err) { /* ... */ });
sink.write("2,Bob\n", function (err) { /* ... */ });
sink.close(function (err) {
if (err != null) { print("close failed:", err); return; }
print("report written");
});
Best Practices
- Use the async variant in long-running programs; reach for sync only in scripts and one-shots.
- Avoid mixing concurrent
write_filecalls to the same path — they overwrite each other. - For streaming writes, always call
close()and use its callback to confirm the data is durable. - Be careful with overwrite:
write_filetruncates without asking. Check withio.existsfirst if that's a concern.