The fs module gives you access to the file system. The sync variants (readFileSync, writeFileSync) block the thread — fine for startup scripts, avoid in request handlers. The async variants use callbacks or Promises.
Reading and writing files
const fs = require('fs')
// Write a file
fs.writeFileSync('hello.txt', 'Hello, world!')
// Read it back
const content = fs.readFileSync('hello.txt', 'utf8')
console.log(content) // Hello, world!fs/promises — async/await style
const fs = require('fs/promises')
async function run() {
await fs.writeFile('data.txt', 'some data')
const text = await fs.readFile('data.txt', 'utf8')
console.log(text)
}
run()Streams are used for large files — instead of loading everything into memory, data flows through in chunks:
const readable = fs.createReadStream('bigfile.txt', { encoding: 'utf8' })
readable.on('data', (chunk) => process.stdout.write(chunk))
readable.on('end', () => console.log('\nDone'))The fs module gives you access to the file system. The sync variants (readFileSync, writeFileSync) block the thread — fine for startup scripts, avoid in request handlers. The async variants use callbacks or Promises.
Reading and writing files
const fs = require('fs')
// Write a file
fs.writeFileSync('hello.txt', 'Hello, world!')
// Read it back
const content = fs.readFileSync('hello.txt', 'utf8')
console.log(content) // Hello, world!fs/promises — async/await style
const fs = require('fs/promises')
async function run() {
await fs.writeFile('data.txt', 'some data')
const text = await fs.readFile('data.txt', 'utf8')
console.log(text)
}
run()Streams are used for large files — instead of loading everything into memory, data flows through in chunks:
const readable = fs.createReadStream('bigfile.txt', { encoding: 'utf8' })
readable.on('data', (chunk) => process.stdout.write(chunk))
readable.on('end', () => console.log('\nDone'))