使用 Node.js 写入文件
The easiest way to write to files in Node.js is to use the
Alternatively, you can use the synchronous version
You can also use the promise-based
fsPromises.writeFile() method offered by the
By default, this API will replace the contents of the file if it does already exist.
You can modify the default by specifying a flag:
|Flag||Description||File gets created if it doesn't exist|
|This flag opens the file for reading and writing||❌|
|This flag opens the file for reading and writing and it also positions the stream at the beginning of the file||✅|
|This flag opens the file for writing and it also positions the stream at the end of the file||✅|
|This flag opens the file for reading and writing and it also positions the stream at the end of the file||✅|
- You can find more information about the flags in the fs documentation.
Appending to files is handy when you don't want to overwrite a filewith new content, but rather add to it.
A handy method to append content to the end of a file is
fs.appendFile() (and its
Here is a