使用 Node.js 写入文件

贡献者
目录

Wiriting a file

The easiest way to write to files in Node.js is to use the fs.writeFile() API.

JS

Writing a file synchronously

Alternatively, you can use the synchronous version fs.writeFileSync():

JS

You can also use the promise-based fsPromises.writeFile() method offered by the fs/promises module:

JS

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:

JS

The flags you'll likely use are

FlagDescriptionFile gets created if it doesn't exist
r+This flag opens the file for reading and writing
w+This flag opens the file for reading and writing and it also positions the stream at the beginning of the file
aThis flag opens the file for writing and it also positions the stream at the end of the file
a+This flag opens the file for reading and writing and it also positions the stream at the end of the file

Appending content to a file

Appending to files is handy when you don't want to overwrite a filewith new content, but rather add to it.

Examples

A handy method to append content to the end of a file is fs.appendFile() (and its fs.appendFileSync() counterpart):

JS

Example with Promises

Here is a fsPromises.appendFile() example:

JS