Skip to content

IO

The @std/io module provides console input, file streams, and file writing.

import io from "@std/io"
let name = io.read("Name: ")
println("Hello", name)
NameKindDescription
StreamstructStream returned by io.open.
readfunctionReads text from standard input.
openfunctionOpens a file as a stream.
writeFilefunctionWrites data to a file.

Reads a string from standard input.

Arguments:

NameTypeDefaultDescription
textstring""Prompt text printed before reading.
trimbooltrueWhether to trim surrounding whitespace.
endlnchar'\n'Character that ends input.

Returns: string

import io from "@std/io"
let name = io.read("Name: ")
println(name)

Read without trimming:

import io from "@std/io"
let raw = io.read("Raw: ", false)
println(raw)

Opens a file and returns a Stream.

Arguments:

NameTypeDefaultDescription
filestringnoneFile path.
modestring"r"Open mode.
permintsystem defaultFile permissions for created files.
encodingstring"utf-8"Text encoding.

Returns: Stream

import io from "@std/io"
let stream = io.open("README.md")
println(stream.readAll())
stream.close()

Relative paths are resolved from the current source file when debug file information is available.

ModeDescription
"r"Read-only. File must exist.
"r+"Read/write. File must exist.
"rw"Read/write. File must exist.
"w"Write-only. Create or truncate.
"w+"Read/write. Create or truncate.
"rw+"Read/write. Create or truncate.
"a"Write-only append. Create if needed.
"a+"Read/write append. Create if needed.

Supported encodings:

Name
utf-8
utf-16
utf-16le
utf-16be
latin1
iso-8859-1
windows-1252
cp1252

Writes data to a file.

Arguments:

NameTypeDefaultDescription
filestringnoneFile path.
dataanynoneData to write. Converted to string.
permintsystem defaultFile permissions.
import io from "@std/io"
io.writeFile("hello.txt", "Hello, Nubo")

A Stream supports reading, writing, and closing depending on how it was opened.

MethodReturnsDescription
read()stringReads up to a chunk of data.
readAll()stringReads the rest of the stream.
readByte()byteReads one byte.
readLine()stringReads one line without the trailing newline.
readLines()[]stringReads lines into a list.
import io from "@std/io"
let stream = io.open("notes.txt")
println(stream.readLine())
println(stream.readAll())
stream.close()

Writing methods are available when the stream was opened in a writable mode.

MethodReturnsDescription
write(content)intWrites a string and returns bytes written.
writeByte(content)intWrites one byte and returns bytes written.
import io from "@std/io"
let stream = io.open("out.txt", "w")
stream.write("Hello")
stream.writeByte(byte(10))
stream.write("Nubo")
stream.close()

Always close streams when finished.

import io from "@std/io"
let stream = io.open("out.txt", "w")
stream.write("done")
stream.close()