Lesson contents

File input and output

Create the small text file shown here next to your program. The program opens it, reads the saved text, and prints it on screen.

Simple example

Read a saved number.

Startinput.txt
Result3
input.txt
3
lesson.ts
declare function require(name: "node:fs"): { readFileSync(path: string, encoding: "utf8"): string };

const text = require("node:fs").readFileSync("input.txt", "utf8");
console.log(text.trimEnd());
Output
3
Advertisements

Everyday examples

The library leaves the next reservation number in a file. Read the slip number so the next shift can call the right learner.

Startinput.txt
ResultB12
input.txt
B12
lesson.ts
declare function require(name: "node:fs"): { readFileSync(path: string, encoding: "utf8"): string };

const text = require("node:fs").readFileSync("input.txt", "utf8");
console.log(text.trimEnd());
Output
B12
Run the example
Terminal
tsc --target ES2020 lesson.ts
node lesson.js
Official documentation