Writing Files in Node.js

Writing Files Featured Image

Writing files in Node.js is yet another common basic task, developers need to about and carry out on a regular basis. Fortunately, this task has been made easy with the help of one of Node’s core built-in modules which we are talking about today.

Node.js is a JavaScript-based runtime, conducts multiple features to make our apps immensely flexible and powerful.

Getting Started with Writing Files in Node.js

Similar to reading files, Node.js can write files too and in a precise manner. With help of the writeFile() method on the fs i.e. file system module, it is easier to do so.

As I have mentioned in the linked post below, all core Node modules have both synchronous and asynchronous forms. The writeFile() shall have both forms being a core module.

Click here to learn how to read files in Node.js.

Before we proceed any further, let us include our fs module in our project.

const fs = require('fs');

fs.writeFile(filename, data, [encoding], [callback])

  • filename – String, the path of the file to be written
  • data – String or Buffer, data you want the file to contain
  • options – Object
    • encoding – String (optional), encoding of the file; default = ‘utf8’
    • flag – String, default = ‘w’
  • callback – (optional function (error) {}) if no error present, then err === null, otherwise err will be the error message

File encoding refers to the character sets used by the contents of a file. As mentioned above, ‘utf8’ encoding is very common and hence set as default too.

An UTF-8 encoding, is commonly for webpages and most documents. Other most common encodings are ‘ascii’, ‘binary’, ‘hex’, ‘base64’ and ‘utf16le’.

Let’s start by writing a groceries list for Cassandra in a file, using the asynchronous form:

const content = 'Bread' +
             'Tomatoes' +
             'Eggs';

fs.writeFile('/Users/Cassandra/list.txt', content, err => {
  if (err) {
    console.error(err)
    return
  }
     // success case, the file was saved
    console.log('List saved!');
})

fs.writeFileSync()

Now, let’s do the same in asynchronous form, using writeFilesync():

const content = 'Bread' +
             'Tomatoes' +
             'Eggs';

try {
  const data = fs.writeFileSync('/Users/Cassandra/list.txt', content)
     // success case, the file was saved
    console.log('List saved!');
} catch (err) {
  console.error(err)
}

Remember, if the file already exists, this API will replace all the contents entirely.

However, there’s a way you can modify the default behavior by specifying a flag:

fs.writeFile('/Users/Cassandra/list.txt', content, { flag: 'a+' }, err => {})

The flags you can use according to your requirements such as appending or prepending streams:

  • r+ – opens the file for reading and writing. An error occurs if the file doesn’t exist.
  • w+ – opens the file for reading and prepending the stream at the beginning of the file. Creates the file if it does not exist.
  • a – opens the file for appending the stream at the end of the file. Creates the file if it does not exist.
  • a+ – opens the file for reading and appending the stream at the end of the file. Creates the file if it does not exist.

Find more flags here on the official documentation of Node.js.

Conclusion

Similar to reading files, Node.js can write files and in a precise manner. Writing files in Node.js is yet another common basic task, developers need to about and carry out on a regular basis.

Read More: How to Contribute to Node.js Core

Noteworthy References

Node.js Writing Files API – Official Docs