Appending to Files
Appending adds data to the end of a file instead of replacing it — the natural operation for logs, audit trails, and any file that grows over time. Node offers appendFile for one-off additions and write streams for high-frequency appends. The subtle part is doing it efficiently and safely when writes come fast.
appendFile
import { appendFile } from 'node:fs/promises'
// Creates the file if missing, otherwise adds to the end:
await appendFile('app.log', `${new Date().toISOString()} started\n`)
await appendFile('app.log', 'another line\n')It's writeFile with a flag
Under the hood, appendFile(path, data) is exactly writeFile(path, data, { flag: 'a' }). The flag is what flips truncate-and-write into add-to-end:
import { writeFile, appendFile } from 'node:fs/promises'
await writeFile('x.txt', 'line\n', { flag: 'a' }) // same as appendFile
await appendFile('x.txt', 'line\n') // the idiomatic formThe hidden cost of frequent appends
Efficient repeated appends — open once
import { createWriteStream } from 'node:fs'
// flags: 'a' → append mode; the file handle stays open
const log = createWriteStream('app.log', { flags: 'a' })
log.write(`${Date.now()} request received\n`)
log.write(`${Date.now()} response sent\n`)
// …keep writing for the life of the process
process.on('exit', () => log.end())A tiny logger
import { createWriteStream } from 'node:fs'
function createLogger(path) {
const stream = createWriteStream(path, { flags: 'a' })
return {
log: (msg) => stream.write(`${new Date().toISOString()} [INFO] ${msg}\n`),
error: (msg) => stream.write(`${new Date().toISOString()} [ERROR] ${msg}\n`),
close: () => stream.end(),
}
}
const logger = createLogger('app.log')
logger.log('server started')
logger.error('connection dropped')Concurrency and interleaving
Don't reinvent production logging
When to use what
Situation | Use |
|---|---|
Occasional append (a few times) |
|
Frequent appends in one process |
|
Production application logging | A library ( |
Many processes, one log file | Single writer or per-process files |