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?
IntermediateAnswer
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 existsReal-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.