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:
const fs = require('fs')
const content = 'Some content!'
fs.writeFile('/Users/flavio/test.txt', content, (err) => {
if (err) {
console.error(err)
return
}
//file written successfully
})
Alternatively, you can use the synchronous version fs.writeFileSync()
:
const fs = require('fs')
const content = 'Some content!'
try {
const data = fs.writeFileSync('/Users/flavio/test.txt', content)
//file written successfully
} catch (err) {
console.error(err)
}
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:
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:
const content = 'Some content!'
fs.appendFile('file.log', content, (err) => {
if (err) {
console.error(err)
return
}
//done!
})
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.