File System (fs)
Reading, writing, and managing files with Node's fs module
Skills taught: node.fs-module, node.read-write-files, node.fs-promises, node.file-operations
Reading and writing files
const fs = require('fs');
const path = require('path');
// ── Synchronous (simple, blocking) ──
try {
const content = fs.readFileSync(path.join(__dirname, 'notes.txt'), 'utf8');
console.log('File contents:\n', content);
} catch (err) {
if (err.code === 'ENOENT') console.error('File not found:', err.path);
else throw err;
}
// Write / overwrite a file
fs.writeFileSync(path.join(__dirname, 'output.txt'), 'Hello, Node.js!\nLine 2');
console.log('Written: output.txt');
// Append to a file
fs.appendFileSync(path.join(__dirname, 'output.txt'), '\nLine 3 (appended)');
// Check if a file exists
const exists = fs.existsSync(path.join(__dirname, 'output.txt'));
console.log('output.txt exists:', exists);
// Read back what we wrote
const result = fs.readFileSync(path.join(__dirname, 'output.txt'), 'utf8');
console.log('Read back:', result);
// ── Modern async/await with fs.promises ──
const { readFile, writeFile, readdir, stat } = require('fs').promises;
const path = require('path');
async function processFiles() {
const dir = __dirname;
// List directory contents
const files = await readdir(dir);
console.log('Files in', dir + ':', files);
// Read a JSON file
try {
const raw = await readFile(path.join(dir, 'data.json'), 'utf8');
const data = JSON.parse(raw);
console.log('Loaded', data.length, 'records');
data.forEach(user => console.log(' -', user.name));
} catch (err) {
console.error('Read failed:', err.message);
}
// Write a new file
const report = JSON.stringify({ generatedAt: new Date().toISOString(), count: 42 }, null, 2);
await writeFile(path.join(dir, 'report.json'), report);
console.log('Report saved.');
// Get file stats
const info = await stat(path.join(dir, 'package.json'));
console.log('package.json size:', info.size, 'bytes, modified:', info.mtime.toISOString());
}
processFiles().catch(console.error);
Frequently Asked Questions
How do I read a JSON file in Node.js?
Two ways: (1) fs: `const data = JSON.parse(fs.readFileSync('data.json', 'utf8'))` — always specify 'utf8' encoding. (2) In Node 20+ with `"type": "module"`, you can use `import data from './data.json' assert { type: 'json' }`. The fs approach works in both CJS and ESM and is more explicit.