Working with the File System in TypeScript: A Practical Guide

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Introduction: Why Work with the File System in TypeScript



TypeScript, being a strictly typed superset of JavaScript, provides developers with powerful tools for working with the file system. Whether you are creating a utility for processing logs, a web server with file uploads, or a data migration tool — the ability to effectively interact with the file system is a fundamental skill.



In this article, we will explore practical aspects of working with the file system in TypeScript using the built-in fs (File System) module from Node.js. All examples will be accompanied by detailed comments and explanations. We will cover synchronous and asynchronous methods, working with paths, and data typing.



1. Project Setup and Importing the fs Module



Before getting started, you need to set up a TypeScript project. Make sure you have Node.js and the npm package manager installed. Create a new project and install the types for Node.js:



npm init -ynpm install typescript @types/node --save-devnpm install ts-node --save-dev


Create a tsconfig.json file and add basic settings to it:



{  "compilerOptions": {    "target": "ES2020",    "module": "commonjs",    "strict": true,    "esModuleInterop": true,    "outDir": "./dist",    "rootDir": "./src"  },  "include": ["src/**/*"]}


Now, in your index.ts file, import the fs and path modules:



import * as fs from 'fs';import * as path from 'path';


Important: In TypeScript, we use import * as to import the entire module. This ensures full typing of all methods.



2. Reading Files: Synchronous and Asynchronous Approaches



2.1 Asynchronous Reading (Recommended Method)



In TypeScript, it is preferable to use asynchronous methods as they do not block the main execution thread. Consider an example of reading a text file:



import * as fs from 'fs/promises';import * as path from 'path';

async function readFileExample(filePath: string): Promise<string> { try { const absolutePath = path.resolve(filePath); const content: string = await fs.readFile(absolutePath, 'utf-8'); return content; } catch (error) { if (error instanceof Error) { throw new Error(`Error reading file: ${error.message}`); } throw error; }}

// Usage(async () => { const data = await readFileExample('./data/example.txt'); console.log('File content:', data);})();


Note the use of fs/promises — this is the promise-based version of the module, which integrates perfectly with async/await in TypeScript.



2.2 Synchronous Reading (For Simple Scenarios)



Sometimes, for example, when loading a configuration at startup, you can use synchronous methods:



import * as fs from 'fs';import * as path from 'path';

function readConfigSync(configPath: string): Record<string, unknown> { const fullPath = path.join(__dirname, configPath); const rawData = fs.readFileSync(fullPath, 'utf-8'); return JSON.parse(rawData);}

const config = readConfigSync('./config.json');console.log('Configuration:', config);


3. Writing and Modifying Files



3.1 Writing Data to a File



To write data to a file, use writeFile. TypeScript allows you to strictly type data before writing:



import * as fs from 'fs/promises';

interface UserData { id: number; name: string; email: string;}

async function saveUserData(users: UserData[]): Promise<void> { const jsonString: string = JSON.stringify(users, null, 2); await fs.writeFile('./users.json', jsonString, 'utf-8'); con

Blogs

Book Recommendations