Node file read-write mode

When using Nodejs do some scaffolding, and an intermediate service, often encounter file read and write operations. For the contents of the file, we often choose "delete file, and then create a file" complex and transactional features for file operations does not exist!

fs.unlink(filePath, err => {})
fs.writeFile(file, data, err => {})

In fact, for a file with a different opening acts, by opening different behaviors, we can achieve different effects. Such as:

  • Create or replace the original file
  • To replace the existing original file
  • Additional content to the existing original file
  • The existing file overwrite the original content from the beginning of the file
fs.writeFile(file, data[, options], callback)

options <Object> | <string>

  • encoding <Object> | <string>Set file encoding, default: 'utf8'
  • mode <integer>Set the file mode (permissions), Default: 0o666
  • flag <string>File Open behavior default: 'w'

Examples

test.txt initial content file 123

fs.writeFile('test.txt', 'a', { flag: `${flag}` }, () => {
  console.log('success')
})
Flag description test.txt content
r Open the file for reading. If the file does not exist, an exception occurs '123' (unchanged)
r+ Open the file for reading and writing . If the file does not exist, an exception occurs 'A23'
rs+ Open the file in the synchronous mode for reading and writing . Instructs the operating system to bypass the local file system cache ( performance impact ) 'A23'
w Open the file for writing. Then create a file if the file does not exist, if the file already exists it is truncated file ‘a’
wx And 'w'similar, but fail if the path already exists '123' (unchanged)
w+ Open the file for reading and writing . Then create a file if the file does not exist, if the file already exists it is truncated file a
wx+ And 'w+'similar ( read and write ), but if the failed path already exists '123' (unchanged)
a Open the file for Append. If the file does not exist, create the file '123a'
ax And 'a'similar, but fail if the path already exists '123' (unchanged)
a+ Open the file for read and append . If the file does not exist, create the file '123a'
ax+ And 'a+'similar ( read and append ), but failed if the path already exists '123' (unchanged)
as Open the file in synchronous mode for added. If the file does not exist, create the file '123a'
as+ Open file for synchronous mode read and append . If the file does not exist, create the file '123a'

Here Insert Picture Description

Reference address

  • http://nodejs.cn/api/fs.html#fs_file_system_flag
Published 257 original articles · won praise 868 · Views 1.18 million +

Guess you like

Origin blog.csdn.net/ligang2585116/article/details/104336143