Node.js › File System & File Processing

What is the purpose of the 'flag' option in fs.writeFile(), and what's the difference between 'w', 'a', and 'wx' flags?

Intermediate

Answer

The flag option controls how the file is opened for writing: 'w' truncates the file if it already exists (or creates it if not), completely overwriting any existing content; 'a' appends new content to the end of the file, preserving what's already there; 'wx' behaves like 'w' but fails with an error if the file already exists, useful for ensuring you don't accidentally overwrite existing data when a file is genuinely expected not to exist yet.
await fs.promises.writeFile('output.txt', 'new content', { flag: 'w' }); // overwrites
await fs.promises.writeFile('log.txt', 'new entry\n', { flag: 'a' }); // appends
await fs.promises.writeFile('unique.txt', 'data', { flag: 'wx' }); // fails if already exists
Real-world example A report-generation script uses the 'wx' flag specifically when creating a new dated report file, deliberately failing loudly with an error if a report for that date somehow already exists, rather than silently overwriting what could be an important existing file.

Common follow-ups: What specific error code does Node.js throw when a 'wx' write fails because the file already exists?;How do these flags map to the lower-level POSIX file-open flags they're based on?