/

Writing Files with Node.js

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
2
3
4
5
6
7
8
9
10
11
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():

1
2
3
4
5
6
7
8
9
10
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:

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 writing
  • w+: open the file for reading and writing, positioning the stream at the beginning of the file. The file is created if not existing
  • a: open the file for writing, positioning the stream at the end of the file. The file is created if not existing
  • a+: 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
2
3
4
5
6
7
8
9
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.