Writing Files with Node.js
Learn how to write files using Node.js and make use of the fs.writeFile()
API for an easy and efficient approach.
Example:
Here is an example of how to write a file using the fs.writeFile()
API:
1 | const fs = require('fs') |
Alternatively, you can use the synchronous version fs.writeFileSync()
:
1 | const fs = require('fs') |
By default, this API will replace the contents of the file if it already exists.
Modifying Default Settings
You can modify the default behavior by specifying a flag:
1 | fs.writeFile('/Users/flavio/test.txt', content, { flag: 'a+' }, (err) => {}) |
The flags you’ll likely use are:
r+
: open the file for reading and writingw+
: open the file for reading and writing, positioning the stream at the beginning of the file. The file is created if not existinga
: open the file for writing, positioning the stream at the end of the file. The file is created if not existinga+
: open the file for reading and writing, positioning the stream at the end of the file. The file is created if not existing
For more available flags, refer to the Node.js documentation.
Appending to a File
To append content to the end of a file, you can use the fs.appendFile()
method:
1 | const content = 'Some content!' |
Using Streams
Instead of writing the full content to the file before returning the control back to your program, a better option is to use streams to write the file content.