How to Read a File in NodeJS

Reading Files Featured Image

Reading files in Node.js is a very common programming task carried out by Node developers. Node’s core API makes it even easier to do it. File reading in Node.js can be accomplished through the core built-in fs module, also known as the File System module.

The fs module comes with a bunch of file system methods all packed in one module. All methods come in synchronous and asynchronous forms.

In an asynchronous form, the last argument is always a completion callback. The arguments passed to the callback depend on the method. However, the first argument is always reserved for an error/exception.

If in case, the operation fails to complete, the first argument will be undefined otherwise, it will be null.

In the synchronous version of a method, any error is thrown immediately. To handle errors in synchronous forms, we can always make use of try/catch or simply allow them to bubble up.

Getting Started with Reading Files in Node.js

Before we proceed any further, we will first include the fs module in our project.

const fs = require('fs');

Don’t get what the Require module does? Read about it here.

fs.readFile(file[, options], callback)

  • file – String, filename, or file descriptor
  • options: Object
    • encoding – String, default = null
  • callback:
    • err – Error
    • data – String

The fs.readFile() facilitates the simplest way to read a file in Node.js. For the arguments/parameters for this method, we must pass a file path, encoding, and a callback function that accepts the error and the file data as arguments.

This callback function will be called with that data and the error.

The encoding argument is optional and specifies what type of encoding is used to read the file. In most cases, the encodings are ‘utf8‘, ‘ascii‘, and ‘base-64’. When no encodings are passed, the default is specified as null.

The callback argument or parameter is a function that is called when the file has been read and the contents are ready. It accepts two arguments, error and data.

When there are no exceptions, the error parameter will be null and the data parameter will hold the file contents; otherwise err will contain the error message.

Asynchronously Reading Entire File Contents:

fs.readFile('/Users/Cassandra/groceries.txt', 'utf8' , (err, data) => {
  if (err) {
    console.error(err)
    return
  }
  console.log(data)
})

fs.readFileSync(file[, options])

With the readFileSync() method, we can synchronously read files In Node.js. By using this method, we are telling Node.js to block other operations/code that might be running simultaneously, and execute just this operation, that is, reading files.

Node.js then waits for this operation to complete, and once this completes, it will then proceed with executing the remaining operations.

  • file – String, filename or file descriptor
  • options: Object
    • encoding – String, default = null
    • flag – String, default = ‘r’

Encoding

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.

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

Flags

The flags you can use according to your requirements such as opening or reading streams:

  • r – opens the file to read. An error occurs in case of any exceptions.
  • 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.

Synchronously Reading Entire File Contents:

try {
  const data = fs.readFileSync('/Users/Cassandra/groceries.txt', 'utf8')
  console.log(data)
} catch (err) {
  console.error(err)
}

The contents of the should now be visible to you provided, you have permission to read the file. In case you pass an invalid file, then Node will simply spit its basic Error object.

This is usually helpful since you can access and log the err.stack as it contains the stack trace to the point/location as to where exactly the Error object resulted.

Both fs.readFile() and fs.readFileSync() will read the entire contents of the file in memory before returning the file data. This also means that if your files are big, it will have a considerable amount of impact on your memory consumption as well as the execution of your app.

Conclusion

File reading in Node.js is a very common programming practice. It can be easily accomplished through the core built-in fs module, also known as the File System module. The fs module comes with a bunch of file system methods that can be used for a ton of purposes.

Read More: Writing Files with Node.js

Noteworthy References

Node.js File System API – Official Docs

Reading Files with Node.js – Official Docs