typescriptbeginner
Read and Write JSON Files
Read, parse, modify, and write JSON files with proper error handling using Node.js fs module.
typescriptPress ⌘/Ctrl + Shift + C to copy
import { readFile, writeFile } from 'fs/promises';
import { existsSync } from 'fs';
import path from 'path';
interface Config {
port: number;
host: string;
debug: boolean;
features: string[];
}
// Read JSON file
async function readJSON<T>(filepath: string): Promise<T> {
const raw = await readFile(filepath, 'utf-8');
return JSON.parse(raw) as T;
}
// Write JSON file (pretty-printed)
async function writeJSON<T>(filepath: string, data: T): Promise<void> {
const json = JSON.stringify(data, null, 2);
await writeFile(filepath, json + '\n', 'utf-8');
}
// Read with fallback defaults
async function readJSONOrDefault<T>(filepath: string, defaults: T): Promise<T> {
if (!existsSync(filepath)) return defaults;
try {
return await readJSON<T>(filepath);
} catch {
return defaults;
}
}
// Usage
const configPath = path.join(process.cwd(), 'config.json');
const defaults: Config = {
port: 3000,
host: 'localhost',
debug: false,
features: [],
};
const config = await readJSONOrDefault<Config>(configPath, defaults);
console.log('Config:', config);
// Modify and save
config.debug = true;
config.features.push('new-feature');
await writeJSON(configPath, config);
console.log('Saved updated config');Use Cases
- Configuration file management
- Data persistence without a database
- Reading package.json or manifest files
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptbeginner
Directory Operations with fs
Create, read, copy, and remove directories recursively using Node.js fs/promises.
Best for: Build tool directory management
#nodejs#fs
typescriptadvanced
Node.js Worker Threads for Parallel Processing
Use Worker Threads to run CPU-intensive tasks in parallel without blocking the event loop.
Best for: CPU-intensive data processing without blocking
#nodejs#worker-threads
typescriptintermediate
Node.js Stream Pipeline with Transform
Build efficient data processing pipelines using Node.js streams for large file handling.
Best for: Processing large CSV files without loading into memory
#nodejs#streams
typescriptintermediate
TypeScript Typed Event Emitter
Create type-safe event emitters in Node.js with full TypeScript support and autocomplete.
Best for: Type-safe pub/sub communication between modules
#nodejs#events