How to append files in Node.js
Appending files in Node.js allows you to add new content to existing files without overwriting previous data, essential for logging, data collection, and incremental file updates. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented file appending in countless Node.js applications for logging systems, data processing, and content management. From my expertise, the most effective approach is using fs.appendFile() for simple operations and fs.createWriteStream() for high-performance scenarios. This method provides efficient file writing with proper error handling and optimal performance for various use cases.
Use fs.appendFile() to add content to existing files without overwriting previous data.
import { appendFile } from 'fs/promises'
import { createWriteStream } from 'fs'
// Simple append operation
async function appendToFile() {
try {
await appendFile('log.txt', 'New log entry\n')
console.log('Data appended successfully')
} catch (error) {
console.error('Append failed:', error)
}
}
// High-performance streaming append
function appendWithStream() {
const stream = createWriteStream('data.txt', { flags: 'a' })
stream.write('First line\n')
stream.write('Second line\n')
stream.end()
stream.on('finish', () => {
console.log('Stream writing completed')
})
}
// Append with timestamp
async function logWithTimestamp(message) {
const timestamp = new Date().toISOString()
const logEntry = `[${timestamp}] ${message}\n`
await appendFile('app.log', logEntry)
}
The fs.appendFile() method adds content to the end of existing files or creates new files if they don’t exist. Use createWriteStream with ‘a’ flag for multiple append operations. Always handle errors with try/catch blocks for robust file operations.
Best Practice Note:
This is the same file appending approach we use in CoreUI Node.js applications for logging and data collection systems.