Here are some common flags used in NodeJS:
'a'
: Open file for appending. The file is created if it does not exist.'w'
: Open file for writing. The file is created (if it does not exist) or truncated (if it exists). This is the default flag.'r'
: Open file for reading. An exception occurs if the file does not exist.'ax'
: Like 'a'
but fails if the path exists. The ‘x’ in the ‘ax’ flag stands for “exclusive”.'wx'
: Like 'w'
but fails if the path exists.Here is an example of how to use these flags:
// Append to the file
fs.writeFileSync("test.json", "[\n", { flag: 'a' })
// Write to the file (default behavior)
fs.writeFileSync("test.json", JSON.stringify(data, null, 2))
// Open file for reading
fs.readFileSync("test.json", { flag: 'r' })