Back to results for “Performance”
Node.js › File System & File Processing

What is the difference between fs.appendFile() and opening a file with the 'a' flag and writing to it manually?

Intermediate

Answer

fs.appendFile() is a convenience method that internally opens the file in append mode, writes the data, and closes the file, all in one call -- functionally equivalent to manually opening a file descriptor with fs.open(path, 'a'), writing with fs.write(), and closing with fs.close(), but appendFile() is simpler for one-off appends, while manually managing the file descriptor is preferable when writing many times to the same file, avoiding the overhead of repeatedly opening and closing it.
// Simple one-off append
await fs.promises.appendFile('log.txt', 'New log entry\n');

// More efficient for many repeated writes to the same file
const fd = await fs.promises.open('log.txt', 'a');
for (const entry of manyLogEntries) { await fd.appendFile(entry + '\n'); }
await fd.close();
Real-world example A logging utility writing thousands of log entries per minute keeps a single open file descriptor via fs.open() rather than calling fs.appendFile() (which reopens and recloses the file every single time) for each entry, significantly reducing file-system overhead under high log volume.

Common follow-ups: What's the actual performance difference between repeatedly using appendFile() versus keeping a file descriptor open, under realistic load?;What happens if two separate processes both try to append to the same file concurrently?