typescriptbeginner

Read and Write JSON Files

Read, parse, modify, and write JSON files with proper error handling using Node.js fs module.

typescript
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.