Make TaskKit ask for its tasks while it runs. Ask a question with readline and wait for the answer with await, see why every answer arrives as a string and why a program that never closes its reader never ends, keep asking until an empty line, and give TaskKit an interactive mode: npm start add with nothing after it asks for the tasks one by one.
Fundamentals
TypeScript
Interactive input with `readline`. Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
Lesson 2.8 warned you about the quotes, and they are still easy to
forget. Type npm start add buy milk without them (npm, the Node
package manager, runs TaskKit's start script), and TaskKit adds two
tasks, Buy and Milk, and saves both to tasks.json. The terminal
split the line at the space before TaskKit ever saw it.
Think of two ways to order at a café. One is an order form you fill
in completely and hand over: every box at once, before anyone reads
it. The other is the person at the counter, who asks one question at
a time and waits for each answer. So far TaskKit has worked like the
form. In this lesson it learns to ask: npm start add with nothing
after it asks for your tasks one by one, and each line you type is
one whole task, spaces and all.
Asking while the program runs
Until now, TaskKit got everything it knew at the start: the words
after the command (process.argv, lesson 2.8), and since lesson 12.2
the file tasks.json. Once it was running, it never listened to you
again. Interactive input is input a program asks for while it
runs: it prints a question, stops, and goes on with your answer.
A program you start in the terminal is joined to it in two
directions. Standard input is what you type into the running
program; Node calls it process.stdin. Standard output is where
the program's text goes, the place console.log writes; Node calls
it process.stdout. A question goes out on standard output, and your
answer comes back on standard input. Here is one exchange, arrow by
arrow. Press Next step to walk through it, or let it play:
You
Terminal
TaskKit
1
TaskKit to Terminal: Tasktoadd:
2
You to Terminal: buymilk
TaskKit asks and stops; your Enter sends the line back as a
string, and an empty one ends the questions
All 7 steps shown.Step 1 of 7: TaskKit → Terminal — Task to add:Step 2 of 7: You → Terminal — buy milk ⏎Step 3 of 7: Terminal → TaskKit — "buy milk"Step 4 of 7: TaskKit → Terminal — Task to add:Step 5 of 7: You → Terminal — ⏎ aloneStep 6 of 7: Terminal → TaskKit — ""Step 7 of 7: TaskKit → Terminal — Added: Buy milk
All 7 steps shown.
While you type, your code gets nothing: the terminal hands over the
line only when you press Enter, the ⏎ in the figure. The dashed
arrows are those answers.
reader.question: one question, one answer
Node has a module for asking, node:readline, short for read a
line. Like node:fs/promises in lesson 12.2,
node:readline/promises is the form of it this course uses, where
the function that waits for you gives back a promise. The page cannot
run it, because there is no keyboard behind a page's Run, so this
one runs in your terminal. In ~/projects/taskkit, make greet.ts:
createInterface makes a reader: an object that reads whole
lines from input and writes its questions to output, here the
terminal's two directions. Its name has nothing to do with
TypeScript's interface from lesson 6.4: here, an interface is the
connection between your program and the terminal.
reader.question prints its text and waits until you press Enter.
It gives back a Promise<string>, and the string is the line you
typed, without the Enter. Line 6 waits for it with await, at the
top of the file as in lesson 12.2, so line 7 runs only once you have
answered. Run it, type Ana after the question, and press Enter
(Return on a Mac):
The space at the end of "What is your name? " keeps your answer off
the question mark. Whatever you type comes in this way, as text, and
digits are no exception. Press Next step to follow 25 in, or
let it play:
You type 25 ⏎
Two keys and Enter, at the question How many minutes?.
reader.question(…)
The edge of your program: the line comes in as typed, without the
Enter.
answer: "25"
A string of two characters, not a number: answer + 5 is "255".
Number(answer): 25
A number, made by you, as lesson 2.8 did with process.argv.
Digits typed at a question come in as text, as every answer
does
All 4 steps shown.Step 1 of 4: You type 25 ⏎Step 2 of 4: reader.question(…)Step 3 of 4: answer: "25"Step 4 of 4: Number(answer): 25
All 4 steps shown.
close: let the program end
The last line of greet.ts, reader.close(), looks like tidying
up, and it is the line that lets the program finish.
Bad — no close, so the program
prints Hi, Ana! and the terminal never gives you its prompt back.
Good — reader.close() on the last
line, highlighted, and the program ends after it.
A reader keeps listening to the keyboard until it is closed, and Node
does not end a program that is still listening. If a program stops
like the first one and never gives the prompt back, end it the way
you stopped an endless loop in lesson 4.2:
⌃ Control+C
Ctrl+C
Ctrl+C
Without close, every run of TaskKit would end with you pressing
those keys.
Asking until the list is done
One question gives one answer. For a list of tasks, TaskKit has to
ask again and again until you say you are done, which is a job for
the while loop of lesson 4.2. Make ask-list.ts:
Line 7 asks once before the loop, so that the while has an answer
to look at. Each turn keeps that answer in titles and asks again,
on line 10. When an answer is empty, the loop ends, the reader is
closed, and the list is printed. answer.trim() makes a line of only
spaces count as empty too. Run it, type two tasks, then press Enter
on an empty line:
buy milk came in as one task, space and all, with no quotes.
Predict before you run
This is ask-list.ts with one change: the last line prints how many
tasks the list holds. Before you run it, decide what happens when you
type the same task twice.
Predict
You type buy milk, then buy milk again, then press Enter on
an empty line. What is printed last?
The common mistake: the old readline
The two imports differ by one word, and many examples online use the
older one, so it is an easy slip.
Common mistake
Importing createInterface from node:readline
You write greet.ts from memory, and the import, on the highlighted
first line, loses its /promises:
npm run check prints its two > lines, and then these; TS2554 is
TypeScript's (TS) number for the error. Under the second message it
also quotes a long line of Node's own types, left out here:
node:readline is the older form, written before promises. Its
question gives back nothing to wait for: it wants a second
argument, a callback (lesson 5.4) to call with your answer. The
second message points at that callback in Node's types; its line
numbers may differ on your computer.
Expected 2-3 arguments, but got 1.
The fix
Import from the form with promises, on the first line, and question
takes one argument and gives back a Promise<string> again:
When the check says question wants more arguments, or names a
callback, look at the import before you look anywhere else.
TaskKit: ask for the tasks
TaskKit gets its interactive mode now: npm start add with a task
after it works as before, and npm start add alone asks for the
tasks.
1
Write ask.ts
In ~/projects/taskkit, make ask.ts. It is the loop of
ask-list.ts, as a function that gives the list back:
askTitles waits for every answer, so it is async and gives back a
Promise<string[]>: a promise of the whole list.
2
Ask when no task follows add
In command.ts, add this line at the top:
readCommand will wait for askTitles, so it has to be async too.
Change its first line,
export function readCommand(): Command {, to:
Then, in its switch, change the add case to:
With words after add, nothing changes. With none, titles is empty
and TaskKit asks. Last, in index.ts, readCommand now gives back a
promise, so wait for it: change const command = readCommand(); to:
It stands inside the big try. When readCommand throws, as it does
for npm start with no command, the await throws that error again,
and the catch prints it as before (lesson 11.5).
3
Check, and add two tasks
Your list may still hold tasks from lesson 12.2's runs. Delete
tasks.json in VS Code (Visual Studio Code, your editor) first, so
the list starts empty. Then:
The check prints only its two > lines. Under its banner, TaskKit
asks. Type two tasks, then press Enter on an empty line. These are
the lines under the banner:
The rest of the add case ran exactly as it does for words after
add: each answer was tidied, capitalized and saved. If you press
Enter at the very first question, nothing is added, and on an empty
list TaskKit prints its old hint, Add what? Try: npm start add "buy milk"; the quotes there are still right for that form. Run the
tests too:
They still end with ℹ pass 11 and ℹ fail 0: no function the tests
check has changed.
Pass all four tasks to complete the lesson with practice. Reach the end without them and it counts as read only.
Exercises
Each one is checked in your browser. The page cannot ask you
questions, so three of them ask about code you would run in the
terminal, and one works on lines that have already been typed.
Recap
Recap · 3 questions
Check yourself
What does await reader.question("Task to add: ") give you?
Check yourself
How does the line you type reach your program?
Check yourself
Which import gives you a question you can await?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
Interactive input with readline
What things are
Word
What it means
Interactive input
What a program asks for while it runs
Standard input
What you type into a running program: process.stdin
Standard output
Where console.log writes: process.stdout
node:readline/promises
Node's module for reading lines, with promises
Reader
The object createInterface makes, to ask and read
Code
Write
To
createInterface({ … })
Make a reader; give it input and output
await reader.question("Name? ")
Ask, wait for Enter, get the line
reader.close()
Stop listening, so the program can end
answer.trim() !== ""
The while test: keep asking until an empty line
npm start add
TaskKit asks for the tasks, one per line
Rules
Rule
What it means
An answer is a string
Digits too: use Number(answer) for a number
No close, no end
It waits until Ctrl + C; Control on a Mac
Import /promises
node:readline alone wants a callback: TS2554
Ctrl + C at a question
Rejects it: Aborted with Ctrl+C
Where to go next
You can now ask a question while your program runs, wait for the
answer with await reader.question, keep asking until an empty line,
and close the reader so the program ends. TaskKit asks for its tasks
when nothing follows add, and a task you type at its question needs
no quotes, spaces and all.
Next is fetch: getting data from a web API, where your
program's data comes from a third place outside it: not a file or
your keyboard, but a website. A web API (application programming
interface) is a website that answers programs, with data rather than
pages.
Before you move on, run npm start add, type a task of three words,
then a line of only spaces. Predict what TaskKit adds and whether it
asks again, then open tasks.json to check. If the list is full,
delete tasks.json first.
⏎
3
Terminal to TaskKit: "buymilk"
4
TaskKit to Terminal: Tasktoadd:
5
You to Terminal: ⏎alone
6
Terminal to TaskKit: ""
7
TaskKit to Terminal: Added:Buymilk
4
Clean up
Delete greet.ts, ask-list.ts, and ask-count.ts if you made it:
they are not part of TaskKit.
Exercise · Read the code
The prompt that never comes back
You run this, type buy milk, then press Enter on an empty line. It
prints [ 'buy milk' ], and then the terminal shows no prompt and
takes no command. Why?
Exercise · Predict the result
A task after add
With the interactive mode in place, you run
npm start add "pay rent". How many times does TaskKit print
Task to add:?
Exercise · Read the code
No question before the loop
To save a line, someone starts answer empty instead of asking before
the loop. They run it and type nothing. What happens?
In the terminaltext
What is your name? AnaHi, Ana!
In the terminaltext
Task to add: buy milkTask to add: call MomTask to add:[ 'buy milk', 'call Mom' ]
What the check printstext
greet.ts:6:27 - error TS2554: Expected 2-3 arguments, but got 1.6 const name = await reader.question("What is your name? "); ~~~~~~~~ node_modules/@types/node/readline.d.ts:186:33 - An argument for 'callback' was not provided.Found 1 error in greet.ts:6
What TaskKit printstext
Task to add: buy milkTask to add: call MomTask to add:Added: Buy milkAdded: Call Mom2 tasks added, room for 3 moreList 40% fullYour list, A to Z:#1 [todo] Buy milk, due: not set#2 [todo] Call Mom, due: not set
greet.tsts
import { createInterface } from "node:readline/promises";const reader = createInterface({ input: process.stdin, output: process.stdout,});const name = await reader.question("What is your name? ");console.log(`Hi, ${name}!`);reader.close();
bash
node greet.ts
greet.tsts
import { createInterface } from "node:readline/promises";const reader = createInterface({ input: process.stdin, output: process.stdout,});const name = await reader.question("What is your name? ");console.log(`Hi, ${name}!`);
greet.tsts
import { createInterface } from "node:readline/promises";const reader = createInterface({ input: process.stdin, output: process.stdout,});const name = await reader.question("What is your name? ");console.log(`Hi, ${name}!`);reader.close();
typed holds the lines someone typed at Task to add:, in order.
Put them into titles up to the first empty one, the way askTitles
does: a line of only spaces counts as empty, and nothing after it is
kept.