| 202 | |
| 203 | // Handle incoming data |
| 204 | const onData = (data: Buffer) => { |
| 205 | const char = data.toString() |
| 206 | |
| 207 | // Handle Ctrl+C |
| 208 | if (char === "\x03") { |
| 209 | cleanup() |
| 210 | resolved = true |
| 211 | this.stdout.write("\n[cancelled]\n") |
| 212 | resolve({ value: defaultValue, timedOut: false, cancelled: true }) |
| 213 | return |
| 214 | } |
| 215 | |
| 216 | // Cancel timeout on first input |
| 217 | if (!timeoutCancelled) { |
| 218 | timeoutCancelled = true |
| 219 | clearTimeout(timeout) |
| 220 | } |
| 221 | |
| 222 | // Handle Enter |
| 223 | if (char === "\r" || char === "\n") { |
| 224 | if (!resolved) { |
| 225 | resolved = true |
| 226 | cleanup() |
| 227 | this.stdout.write("\n") |
| 228 | resolve({ value: inputBuffer, timedOut: false, cancelled: false }) |
| 229 | } |
| 230 | return |
| 231 | } |
| 232 | |
| 233 | // Handle Backspace |
| 234 | if (char === "\x7f" || char === "\b") { |
| 235 | if (inputBuffer.length > 0) { |
| 236 | inputBuffer = inputBuffer.slice(0, -1) |
| 237 | this.stdout.write("\b \b") |
| 238 | } |
| 239 | return |
| 240 | } |
| 241 | |
| 242 | // Normal character - add to buffer and echo |
| 243 | inputBuffer += char |
| 244 | this.stdout.write(char) |
| 245 | } |
| 246 | |
| 247 | this.stdin.on("data", onData) |
| 248 | }) |