Reading And Writing To Files

Reading and writing to a file is a common task most developers do. Thankfuly Node.js provides a simple to use package that can be used to read and write to a file synchronously or asynchronously.

Synchronous Reading

Let's take a quick look at reading a file synchronously and asynchronously. The first thing you need to do is require the fs (File System) package.

Listing 1

const fs = require("fs");

To read a file synchronously, the fs package provides a readFileSync() method, which takes one or two arguments. The first is the filename and the second optional arument is an options object, which when supplied, specifies the encoding to use and the read mode.

Listing 2

var data = fs.readFileSync("file.txt");

Note that the readFileSync() method returns data, which is either of type string or Buffer. When no encoding option is supplied, a Buffer object is returned. We can convert the Buffer object to an encoded string using the toString() method as shown below.

Listing 3

var data = fs.readFileSync("test.txt");

The code below shows how to pass the encoding by the optional options object. The output is the same as the code above.

Listing 4

var data = fs.readFileSync("test.txt"{ encoding : "UTF8" });

Asynchronous Reading

Reading files synchronously will block Node.js event loop, which means if you are reading large files, the execution of your code will hault until the file has been read. Node.js provides an asynchronous method to read files, which is used when blocking Node.js event loop is not an option. The code sample below shows how to read a file asynchronously.

Listing 5

fs.readFile("file.txt"{ encoding : "UTF8" }(err, data) => {

Notice that the readFile() method does not return any data but rather accepts a callback function with two arguments (err and data). The callback function is executed when the file has been read or an error occured. You should check the err variable before you attempt to process the data variable.

Node.js also provides synchronous and asynchronous methods to write data to a file. The following code shows how to write data to a file synchronously.

Listing 6

fs.writeFileSync("myfile.txt""Hello World"{ encoding : "UTF8" });

To write a file asynchronously use the writeFile() method.

Listing 7

fs.writeFile("myfile.txt""Hello World"{ encoding : "UTF8" }(err) => {
    // handle error here