0
# Console I/O Operations
1
2
## Overview
3
4
The Console I/O capabilities provide basic output functionality for WASI applications. These functions use the WASI `fd_write` system call to write data to standard output (file descriptor 1).
5
6
## API Reference
7
8
### Output Functions
9
10
```kotlin { .api }
11
/**
12
* Prints the given [message] to the standard output stream.
13
* @param message the object to print
14
*/
15
fun print(message: Any?)
16
17
/**
18
* Prints a line separator to the standard output stream.
19
*/
20
fun println()
21
22
/**
23
* Prints the given [message] and a line separator to the standard output stream.
24
* @param message the object to print
25
*/
26
fun println(message: Any?)
27
```
28
29
### Input Functions (Not Implemented)
30
31
```kotlin { .api }
32
/**
33
* Reads a line from the standard input stream.
34
* @return the line read from the input
35
* @throws TODO Currently not implemented in WASI
36
* @since Kotlin 1.6
37
*/
38
fun readln(): String
39
40
/**
41
* Reads a line from the standard input stream, or returns null if EOF is reached.
42
* @return the line read from the input, or null on EOF
43
* @throws TODO Currently not implemented in WASI
44
* @since Kotlin 1.6
45
*/
46
fun readlnOrNull(): String?
47
```
48
49
## Usage Examples
50
51
### Basic Output
52
53
```kotlin
54
// Print simple text
55
print("Hello ")
56
print("World")
57
// Output: Hello World
58
59
// Print with newlines
60
println("First line")
61
println("Second line")
62
println() // Empty line
63
// Output:
64
// First line
65
// Second line
66
//
67
```
68
69
### Printing Different Types
70
71
```kotlin
72
// Print numbers
73
println(42)
74
println(3.14159)
75
76
// Print boolean values
77
println(true)
78
println(false)
79
80
// Print collections
81
val list = listOf(1, 2, 3)
82
println(list)
83
84
// Print null values
85
println(null)
86
```
87
88
### Formatted Output
89
90
```kotlin
91
val name = "Alice"
92
val age = 30
93
94
// String interpolation
95
println("Name: $name, Age: $age")
96
97
// String formatting
98
println("Pi to 2 decimal places: ${"%.2f".format(3.14159)}")
99
```
100
101
## Implementation Details
102
103
### WASI System Call Integration
104
105
The console output functions are implemented using the WASI `fd_write` system call:
106
107
```kotlin
108
@WasmImport("wasi_snapshot_preview1", "fd_write")
109
private external fun wasiRawFdWrite(
110
fd: Int,
111
iovs: Int,
112
iovsLen: Int,
113
nwritten: Int
114
): Int
115
```
116
117
### Memory Management
118
119
Output operations use scoped memory allocation to safely pass data to WASI:
120
121
- Strings are encoded to UTF-8 bytes
122
- Memory is allocated in WASI linear memory space
123
- IO vectors are constructed for the fd_write call
124
- Memory is automatically cleaned up after the call
125
126
### Error Handling
127
128
Console output operations handle WASI-specific errors:
129
130
- **EBADF**: Bad file descriptor (if stdout is not available)
131
- **EIO**: I/O error during write operation
132
- **ENOSPC**: No space left on device
133
- **EPIPE**: Broken pipe (if output stream is closed)
134
135
All WASI errors are translated to appropriate Kotlin exceptions.
136
137
## Platform Limitations
138
139
### Input Operations Not Supported
140
141
Console input functions (`readln()` and `readlnOrNull()`) are not implemented because:
142
143
1. **WASI Specification Gaps**: WASI preview1 doesn't provide robust stdin reading capabilities
144
2. **Blocking I/O Concerns**: WebAssembly's execution model makes blocking input operations problematic
145
3. **Runtime Environment Variations**: Different WASI runtimes handle stdin differently
146
147
These functions will throw `TODO` exceptions if called:
148
149
```kotlin
150
// This will throw an exception
151
try {
152
val input = readln()
153
} catch (e: NotImplementedError) {
154
println("Console input not available in WASI")
155
}
156
```
157
158
### Output Limitations
159
160
- **Standard Output Only**: Only stdout (fd=1) is supported for output
161
- **No Standard Error**: stderr output is not separately handled
162
- **No File Output**: General file I/O operations are not available through these functions
163
164
## Best Practices
165
166
### Error-Safe Output
167
168
```kotlin
169
// Always handle potential I/O errors
170
try {
171
println("Important message")
172
} catch (e: Exception) {
173
// Log error or use alternative output method
174
}
175
```
176
177
### Performance Considerations
178
179
```kotlin
180
// For multiple outputs, prefer single println over multiple print calls
181
// Less efficient:
182
print("Hello ")
183
print("World")
184
print("!")
185
186
// More efficient:
187
println("Hello World!")
188
```
189
190
### Alternative Input Strategies
191
192
Since console input is not available, consider these alternatives:
193
194
```kotlin
195
// Use command-line arguments for input
196
fun main(args: Array<String>) {
197
if (args.isNotEmpty()) {
198
val input = args[0]
199
println("Processing: $input")
200
}
201
}
202
203
// Use environment variables
204
val config = System.getenv("CONFIG_VALUE") ?: "default"
205
println("Configuration: $config")
206
```