Save TaskKit’s tasks to a file and read them back on the next run. Write text to a file with writeFile, read it back with readFile and “utf8”, see why a missing file stops the first run with ENOENT and how existsSync prevents it, and give TaskKit a store.ts so a task added today is still on the list tomorrow.
Fundamentals
TypeScript
Reading and writing files: `readFile` and `writeFile`. Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
At the end of the last lesson, TaskKit printed its two tasks as JSON
(JavaScript Object Notation, a value written as text), and then you
deleted that console.log line. The text was gone with
it. TaskKit can turn its tasks into text now, but it keeps that text
nowhere, so every run still starts with an empty list.
Think of a meeting room. What is written on the whiteboard is wiped
when the meeting ends; what goes into the notebook in the drawer is
there next week. Your program's memory is the whiteboard. In this
lesson you write TaskKit's tasks into the notebook, a file, and read
them back on the next run. By the end, a task you add today is still
on the list tomorrow.
Memory ends with the run, a file does not
A file, as lesson 1.3 put it, is text saved under a name on your computer's
disk, and the disk keeps it while no program runs, even with the computer off.
index.ts is one. So far only you have made files, in VS Code (Visual Studio
Code, your editor). A program can make one too, and what it writes before it
ends is still there for the next run to read.
So TaskKit needs two new moves. At the start of every run it reads
tasks.json, a file in the taskkit folder, and builds its list from
it. After you add a task, it writes the list back to the same file.
Here are two runs of that, one arrow at a time. Press Next step to
walk through them, or let it play:
You
TaskKit
tasks.json
1
You to TaskKit: add"buymilk"
2
TaskKit to tasks.json: read
3
tasks.json to TaskKit: nofileyet
4
TaskKit to tasks.json:
Each run reads tasks.json first and writes it last; nothing
else survives between the runs
All 8 steps shown.Step 1 of 8: You → TaskKit — add "buy milk"Step 2 of 8: TaskKit → tasks.json — readStep 3 of 8: tasks.json → TaskKit — no file yetStep 4 of 8: TaskKit → tasks.json — write [Buy milk]Step 5 of 8: You → TaskKit — add "call Mom"Step 6 of 8: TaskKit → tasks.json — readStep 7 of 8: tasks.json → TaskKit — [Buy milk]Step 8 of 8: TaskKit → tasks.json — write [Buy milk, Call Mom]
All 8 steps shown.
Between arrows 4 and 5 the first run has ended, and its Map is gone.
Only the file carries Buy milk across. The text in the file is the
JSON that tasksToJson makes from lesson 12.1, so the second run
turns it back into tasks with tasksFromJson.
writeFile: from text to a file
Reading and writing files is not part of JavaScript itself. Node
brings it, in a module called node:fs, short for file system: the
part of the computer that keeps files in folders. The node: at the
front means it comes with Node, as node:test did in lesson 5.11.
node:fs/promises holds the same file functions in the form this
course uses, where every function that waits for the disk gives back a
promise (lesson 11.3).
The pages of this course cannot run file code, so this one runs in
your terminal. In ~/projects/taskkit, make a file write-note.ts:
writeFile takes the file's name and the text to put in it. Writing
takes the disk a moment, so writeFile gives back a
Promise<void>: a wait that ends with no value, only "done". Line 2
waits for it with await, and only then does line 3 print.
That await is not inside an async function. Lesson 11.4's error
said where else await is allowed: "within async functions and at the
top levels of modules". Every .ts file in taskkit is a module
(lesson 9.1), so await may stand on its own at the top of the file,
outside any function. As lesson 11.4 said, there it pauses the rest of
the file: the lines below it wait, which is why line 3 prints only once
the file is written. Run it:
A new file, note.txt, is now in the taskkit folder. Open it in
VS Code: it holds Buy milk and nothing else. If the file is not
there yet, writeFile makes it. If it is, writeFile replaces all
of its text with the new text: the old text is gone.
readFile: from a file back to text
The other direction is readFile. Make read-note.ts next to the
first file:
readFile gives back a Promise<string>, so await gives you the
string: the text of the file. The "utf8", Node's spelling of UTF-8,
says how to read it. On the disk a file is a row of bytes, small
numbers from 0 to 255, and UTF-8 (short for Unicode Transformation
Format, 8-bit; Unicode is the list that gives every letter of every
language a number) is the agreed way to turn letters into bytes and
back again. writeFile used UTF-8 when it wrote the text, and "utf8"
asks readFile to turn the bytes back into letters.
The first run: no file to read
Every run of TaskKit will read tasks.json first, and that has one
problem: on the very first run, nothing has written it yet. See what
readFile does with a file that is not there. In read-note.ts,
change note.txt on line 2 to todo.txt, a file you never made, and
run it again. These are the first lines Node prints; the stack trace,
a block of details and Node.js v24.11.1 follow them:
The first three lines point inside Node's own code, where the read
failed, and their numbers may differ in another version of Node; the
line to read is the one that starts with Error:. ENOENT is
short for error, no entry: there is no file by that name. On
Windows the line names the file with its full path, where the other
two systems repeat the name you gave; it is broken in two here to
fit. The promise from readFile was rejected, await threw the
reason (lesson 11.5), and nothing caught it, so Node stopped.
For TaskKit that is worse than one failed run, because the next run
fails in the same place. The fix is to ask first whether the file is
there, with existsSync. It comes from node:fs. Give it a file
name, and it answers true if the file is there and false if it is
not. Sync is short for synchronous, the opposite of the
asynchronous code of Module 11: it asks the disk and waits right
there, so the program stands still until the answer comes, and it
gives back the answer itself rather than a promise. The question is so
quick that the pause does not matter.
At the end of this lesson you write two functions for TaskKit:
loadTasks reads the list at the start of a run and does that check,
and saveTasks writes the list back after you add a task. Switch
between the two versions, press Next step to walk through one, or
let it play:
Try the check on its own. Replace read-note.ts with this:
Run it, and it prints No todo.txt yet. Make todo.txt in VS Code,
type Pay rent in it, save it, and run node read-note.ts again: it
prints Pay rent. The readFile line now runs only once there is a
file to read.
Predict before you run
This program writes the same file twice, then reads it.
Predict
What does this program print?
The common mistake: reading without "utf8"
"utf8" looks like a detail, and it is the part that is easiest to
leave out.
Common mistake
Reading a file without saying how to turn it into text
You want the note in capital letters. You replace read-note.ts with
this, and the "utf8" gets left out:
npm run check prints its two > lines, and then this; TS2339 is
TypeScript's (TS) number for the error:
Without "utf8", readFile does not turn the bytes into letters: it
gives you the bytes themselves. NonSharedBuffer is Node's type
for a row of raw bytes, and a row of bytes has no toUpperCase.
Property 'toUpperCase' does not exist on type 'NonSharedBuffer'.
The fix
Say how to read the file, and text is a string again:
It prints BUY MILK. When you only print what readFile gave you, the check
does not complain: console.log(text) without "utf8" prints <Buffer 42 75 79 20 6d 69 6c 6b>: the eight bytes of Buy milk, one for each letter and
one for the space. Node writes each number in base 16 (hexadecimal), with the
digits 0 to 9 and then a to f, so 42 is 66, the number for B. So when a
type error names NonSharedBuffer, or the output shows <Buffer …>, look for
the missing "utf8".
TaskKit: tasks that outlast the run
TaskKit has everything it needs now: tasksToJson and
tasksFromJson from lesson 12.1 for the text, and writeFile,
readFile and existsSync for the file.
1
Write store.ts
In ~/projects/taskkit, make a new file, store.ts, for everything
that touches the file:
loadTasks is async because it waits for readFile, so it gives
back a Promise<Map<string, Task>>: a promise of the whole list. On
the first run !existsSync(file) is true, and it returns the empty
Map at once. Otherwise it reads the text, turns it into tasks, and
puts each task in the Map under its title in lower case, the same
key the add case uses for a new task. saveTasks writes the whole
list over the file.
2
Load at the start, save after adding
In index.ts, add this line under the line that imports delay:
Then change the line that makes the empty Map,
const tasks = new Map<string, Task>();, to:
index.ts no longer names Task anywhere, so VS Code greys out
import type { Task } from "./tasks.ts";. Delete that line. Last, in
the add case, put this line right before its break, under the
if that prints Add what?:
It stands inside the big try, and it waits, so if the write ever
fails, the catch at the bottom of index.ts catches it and prints
the reason (lesson 11.5: the try holds the await).
3
Check, and run TaskKit twice
The check prints only its two > lines. These are the last lines
TaskKit prints:
A new file, tasks.json, is in the taskkit folder. Open it: it
holds the same JSON that 12.1's console.log printed, with one task.
Now a second run, with a task that is already on the list:
Buy milk came from the file, so TaskKit knew it was already on the
list. 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 run file code,
so three of them ask about it and one fixes the part of loadTasks
that does not touch the disk.
Recap
Recap · 3 questions
Check yourself
Why may await loadTasks() stand outside any function?
Check yourself
What does readFile give you without "utf8"?
Check yourself
Why does loadTasks ask existsSync first?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
Reading and writing files
What things are
Word
What it means
node:fs
Node's module for files; node:fs/promises gives promises
Byte
A small number from 0 to 255; a file is a row of them
UTF-8
The usual way letters are stored as bytes
NonSharedBuffer
Node's type for raw bytes, not text
ENOENT
Node's code for "no such file"
Code
Write
To
writeFile(file, text)
Make the file, or replace its text; await it
readFile(file, "utf8")
Read the file as a string; await it
existsSync(file)
Ask whether the file is there; no promise
await at the top
Wait outside any function, in a module
await loadTasks()
Build TaskKit's list from tasks.json
await saveTasks(tasks)
Write TaskKit's list to tasks.json
Rules
Rule
What it means
Memory ends with the run
Keep what must last in a file
writeFile replaces
It never adds to the old text
No "utf8", no text
You get bytes, and the check says so
A bare name
Is looked up in the working directory
No file, no read
Ask existsSync before a read that may find no file
Where to go next
You can now write text to a file with writeFile, read it back with
readFile and "utf8", and check with existsSync before a read
that might find nothing. TaskKit keeps its tasks in tasks.json, so a
task you add today is still on the list on the next run.
Next is Interactive input with readline, where TaskKit stops
taking its tasks only as words after npm start and asks you for
them, one question at a time, while it runs.
Before you move on, add three tasks over three runs, one per run.
Before each run, predict what tasks.json will hold afterwards, then
open it and check.
write[Buymilk]
5
You to TaskKit: add"callMom"
6
TaskKit to tasks.json: read
7
tasks.json to TaskKit: [Buymilk]
8
TaskKit to tasks.json: write[Buymilk,CallMom]
You
TaskKit
tasks.json
You: add Buy milkaddBuymilkaddBuymilk
TaskKit: ENOENTENOENTENOENT
TaskKit: stoppedstoppedstopped
tasks.json: never writtenneverwrittenneverwritten
Time
The first run: npm start add "buy milk".
readFile finds no file and rejects:
Error: ENOENT: no such file or directory, naming the file.
Nothing catches it, so Node stops. Buy milk is never added.
Still no file, so the next run stops in the same place.
Without the check, the first run stops before it saves, and
the file never comes into being
All 4 steps shown.Step 1 of 4: You: add Buy milkStep 2 of 4: TaskKit: ENOENTStep 3 of 4: TaskKit: stoppedStep 4 of 4: tasks.json: never written
All 4 steps shown.
You
TaskKit
tasks.json
You: add Buy milkaddBuymilkaddBuymilk
TaskKit: no filenofilenofile
TaskKit: add, saveadd,saveadd,save
tasks.json: 1 task1task1task
Time
The first run: npm start add "buy milk".
existsSync says false, so loadTasks gives an empty Map.
Buy milk goes in the Map, and saveTasks writes it out.
The file exists now: the next run reads it.
Without the check, the first run stops before it saves, and
the file never comes into being
All 4 steps shown.Step 1 of 4: You: add Buy milkStep 2 of 4: TaskKit: no fileStep 3 of 4: TaskKit: add, saveStep 4 of 4: tasks.json: 1 task
All 4 steps shown.
4
Clean up
Delete write-note.ts, read-note.ts, note.txt, and todo.txt and
twice.ts if you made them: they are not part of TaskKit. Keep
tasks.json: it is TaskKit's list now. If you edit it by hand and
break its JSON, the next run stops with 12.1's SyntaxError, because
loadTasks runs before the try; put the text right again, or
delete the file.
Exercise · Read the code
Where the file lands
You are in your home folder, not in taskkit, and you start TaskKit
with Node instead of npm start:
bash
node projects/taskkit/index.ts add "pay rent"
Where does it save tasks.json?
Exercise · Read the code
A run that only reads
tasks.json holds one task, Buy milk. You run npm start help. What
happens to tasks.json?
Exercise · Predict the result
After the file is deleted
In taskkit, with no tasks.json yet, you run
npm start add "buy milk". Then you delete tasks.json in VS Code,
and run npm start add "call Mom". What is the last line the second
run prints?
Outputtext
Saved note.txt
Outputtext
Buy milk
What the check printstext
read-note.ts:3:18 - error TS2339: Property 'toUpperCase' does notexist on type 'NonSharedBuffer'.3 console.log(text.toUpperCase()); ~~~~~~~~~~~Found 1 error in read-note.ts:3
What TaskKit printstext
Added: Buy milk1 task added, room for 4 moreList 20% fullYour list, A to Z:#1 [todo] Buy milk, due: not set
What TaskKit printstext
Added: Call MomAlready on the list: Buy milk2 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
write-note.tsts
import { writeFile } from "node:fs/promises";await writeFile("note.txt", "Buy milk");console.log("Saved note.txt");
bash
node write-note.ts
read-note.tsts
import { readFile } from "node:fs/promises";const text = await readFile("note.txt", "utf8");console.log(text);
bash
node read-note.ts
read-note.tsts
import { existsSync } from "node:fs";import { readFile } from "node:fs/promises";if (existsSync("todo.txt")) { const text = await readFile("todo.txt", "utf8"); console.log(text);} else { console.log("No todo.txt yet");}
twice.tsts
import { readFile, writeFile } from "node:fs/promises";await writeFile("note.txt", "Buy milk");await writeFile("note.txt", "Call Mom");const text = await readFile("note.txt", "utf8");console.log(text);
read-note.tsts
import { readFile } from "node:fs/promises";const text = await readFile("note.txt");console.log(text.toUpperCase());
read-note.tsts
import { readFile } from "node:fs/promises";const text = await readFile("note.txt", "utf8");console.log(text.toUpperCase());
store.tsts
import { existsSync } from "node:fs";import { readFile, writeFile } from "node:fs/promises";import type { Task } from "./tasks.ts";import { tasksFromJson, tasksToJson } from "./tasks.ts";const file = "tasks.json";export async function loadTasks(): Promise<Map<string, Task>> { const tasks = new Map<string, Task>(); if (!existsSync(file)) { return tasks; } const text = await readFile(file, "utf8"); for (const task of tasksFromJson(text)) { tasks.set(task.title.toLowerCase(), task); } return tasks;}export async function saveTasks(tasks: Map<string, Task>): Promise<void> { await writeFile(file, tasksToJson(tasks));}
index.tsts
import { loadTasks, saveTasks } from "./store.ts";
index.tsts
const tasks = await loadTasks();
index.tsts
await saveTasks(tasks);
bash
npm run checknpm start add "buy milk"
bash
npm start add "call Mom" "buy milk"
bash
npm test
What Node printstext
node:internal/fs/promises:642 return new FileHandle(await PromisePrototypeThen( ^Error: ENOENT: no such file or directory, open 'todo.txt'
node:internal/fs/promises:642 return new FileHandle(await PromisePrototypeThen( ^Error: ENOENT: no such file or directory, open'C:\Users\ana\projects\taskkit\todo.txt'
node:internal/fs/promises:642 return new FileHandle(await PromisePrototypeThen( ^Error: ENOENT: no such file or directory, open 'todo.txt'
Exercise · Fix the error
Find the task again
This is the loop at the end of loadTasks, with the tasks from the
file already in saved. The add case looks a task up by its title
in lower case, so tasks.has("call mom") should be true, but the
program prints false. Fix the loop so it prints true.