F

File System

Node.js file system operations with TypeScript provide type-safe file handling.

Code

typescript
1import { readFile, writeFile, readdir, stat } from "fs/promises";
2import { join } from "path";
3
4// Read a file with proper typing
5async function readTextFile(path: string): Promise<string> {
6 const content = await readFile(path, "utf-8");
7 return content;
8}
9
10// Write a file
11async function writeTextFile(path: string, content: string): Promise<void> {
12 await writeFile(path, content, "utf-8");
13 console.log(`Written to ${path}`);
14}
15
16// Read JSON file with type parameter
17async function readJsonFile<T>(path: string): Promise<T> {
18 const content = await readFile(path, "utf-8");
19 return JSON.parse(content) as T;
20}
21
22// Write JSON file
23async function writeJsonFile<T>(path: string, data: T): Promise<void> {
24 const content = JSON.stringify(data, null, 2);
25 await writeFile(path, content, "utf-8");
26}
27
28// List directory contents
29interface FileInfo {
30 name: string;
31 isDirectory: boolean;
32 size: number;
33}
34
35async function listDirectory(dirPath: string): Promise<FileInfo[]> {
36 const entries = await readdir(dirPath);
37
38 const fileInfos = await Promise.all(
39 entries.map(async (name) => {
40 const fullPath = join(dirPath, name);
41 const stats = await stat(fullPath);
42
43 return {
44 name,
45 isDirectory: stats.isDirectory(),
46 size: stats.size,
47 };
48 })
49 );
50
51 return fileInfos;
52}
53
54// Example usage
55async function main(): Promise<void> {
56 // Read package.json
57 interface PackageJson {
58 name: string;
59 version: string;
60 dependencies?: Record<string, string>;
61 }
62
63 const pkg = await readJsonFile<PackageJson>("./package.json");
64 console.log(`Package: ${pkg.name} v${pkg.version}`);
65
66 // List current directory
67 const files = await listDirectory(".");
68 files.forEach((f) => {
69 const type = f.isDirectory ? "[DIR]" : "[FILE]";
70 console.log(`${type} ${f.name} (${f.size} bytes)`);
71 });
72}
73
74main().catch(console.error);

Run this example locally

$ npx ts-node node/file-system.ts