Lesson 3
Writing to Files in TypeScript
Introduction to Writing to Files in TypeScript

In this lesson, we're exploring the powerful capabilities of writing to files using TypeScript with Node.js. Writing files is an essential skill in programming, allowing you to persistently store data, log information, and interact with other systems or users. We'll delve into various modes of file operations using the fs (File System) module, focusing on writing (using fs.writeFileSync), appending (using fs.appendFileSync), and briefly reading (using fs.readFileSync) to confirm our output. TypeScript provides advantages such as type safety, helping to catch errors early during development.

Understanding the Write Mode

Let's begin by exploring how we can write to a file in TypeScript using Node.js. The write mode is used to create a new file or overwrite an existing one.

First, we define the path for the file we want to write to, ensuring type annotations for better clarity:

TypeScript
1import * as fs from 'fs'; 2const outputFilePath: string = 'output.txt';

To write to a file, we'll use fs.writeFileSync, which overwrites the file if it already exists or creates a new one.

TypeScript
1fs.writeFileSync(outputFilePath, "Hello, World!\nThis is a new line of text.\n", 'utf-8'); 2console.log(`Text written to ${outputFilePath} using 'w' mode.`);

Here, we write multiple lines of text, ensuring each ends with a newline character \n. TypeScript's static types allow for catching potential type errors during development. When executed, output.txt will contain:

Plain text
1Hello, World! 2This is a new line of text.
Demystifying the Append Mode

In write mode, any existing content in the file is erased upon opening. This is convenient for starting fresh or completely overwriting existing content. However, if you intend to retain existing data while adding new content, append mode is used, utilizing fs.appendFileSync.

To append text to the end of the file:

TypeScript
1fs.appendFileSync(outputFilePath, "Appending another line of text.\n", 'utf-8'); 2console.log(`Text appended to ${outputFilePath} using 'a' mode.`);

This appends the new line to the existing file content, preserving all original data.

Running this results in:

Plain text
1Hello, World! 2This is a new line of text. 3Appending another line of text.
Checking File Content Using Read Mode

To verify our written and appended content, we can utilize the read mode provided by fs.readFileSync to ensure everything is correctly captured. TypeScript ensures that we handle string data correctly.

Here's how to read the file content:

TypeScript
1const content: string = fs.readFileSync(outputFilePath, 'utf-8'); 2console.log("\nValidating file content:"); 3console.log(content);

By following these steps, the output should confirm the expected contents of your file, assuring you that your program performs as intended.

Writing Numbers to a File

Beyond text, you can also write numbers to a file with fs.writeFileSync. Numbers cannot be directly written into the file and must be parsed into strings before that action

Consider this example of writing a number:

TypeScript
1const number: number = 42; 2fs.writeFileSync(outputFilePath, `The answer to life, the universe, and everything is: ${number}\n`, 'utf-8');

In this example, the number 42 is directly inserted into the string using template literals. After execution, output.txt will contain:

Plain text
1The answer to life, the universe, and everything is: 42

This approach allows you to manage and store numerical and other data effortlessly, accommodating diverse data types while leveraging TypeScript's strengths.

Summary and Preparation for Practice

In this lesson, you've learned to write and append text to files using TypeScript's fs module with methods like fs.writeFileSync and fs.appendFileSync, while validation was performed using fs.readFileSync. These are foundational skills for data storage and management. TypeScript's type safety ensures code reliability and easier debugging. As you proceed to practice exercises, you'll reinforce these concepts with practical applications, preparing you for deeper exploration and usage of Node.js for file manipulation tasks.

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.