Reading files in Node.js can be done using a built-in core module called the fs module. fs module stands for file system module which comes with many synchronous and asynchronous methods used to read and write files.
To use the file system module to interact with files in Node.js, we must first import it in Node.js.
Below is the syntax to import the file system module in Node.js
Syntax:
const fs = require('fs');
Also Read: Node.js File System: Working With Files on NodeJS
Getting Started with Reading Files in Node.js
The File System module has both Asynchronous and synchronous methods to read a file.
In Node, it usually recommends using Asynchronous methods. Asynchronous means non-blocking i.e the method does not block the execution of other methods or operations. But sometimes we want a Synchronous approach such as we want to block other methods or operations until a file is completed read so in this case it is recommended to use a Synchronous method.
Methods to read files in Node.js:
- fs.readFile(): This method is used to read the data of a file asynchronously.
- fs.readFileSync(): This method is used to read the data of a file synchronously.
Both fs.readFile() and fs.readFileSync() will read the entire contents of the file into memory before returning the file data. It means if your files are large, it will have a huge impact on your memory consumption as well as the performance of your app.
Let’s see the details information about both methods.
Reading Files Asynchronously
In an asynchronous method for reading a file, the last argument is always a completion callback, which is automatically executed after the method has completed reading the file.
Syntax:
fs.readFile(file[, options], callback)
where:
- file is the file name or file path of a file to read,
- options hold the encoding of the file and the flags,
- callback is the function that is automatically called when file reading is done, it contains two arguments err and data.
The fs.readFile() facilitates the simplest way to read a file in Node.js. For the arguments for this method, we must pass a file path, encoding, and a callback function.
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 ‘utf8‘.
The callback argument 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.
Example of reading a file asynchronously:
fs.readFile('/Users/Cassandra/groceries.txt', 'utf8' , (err, data) => {
if (err) {
console.error(err)
return
}
console.log(data)
})
Reading Files Synchronously
In a synchronous method for reading a file, errors are thrown immediately. To handle errors synchronously, try/catch blocks can be used.
Syntax:
fs.readFileSync(file[, options])
where:
- file is the file name or file path of a file to read,
- options hold the encoding of the file and the flags
With the readFileSync() method, we can read files synchronously in Node.js. Using this method, we are telling Node.js to block other operations/code running simultaneously and only execute this operation: file reading.
Node.js will then wait for this operation to complete, and once it is done, it will proceed to execute the remaining tasks.
The encoding for this method is also by default ‘uf8’. Other most common encodings are ‘ascii’, ‘binary’, ‘hex’, ‘base64’, and ‘utf16le’.
Flags
The flags can also be used according to the requirements:
- 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.
Example of reading a file synchronously:
try {
const data = fs.readFileSync('/Users/Cassandra/groceries.txt', 'utf8')
console.log(data)
} catch (err) {
console.error(err)
}
The contents of the given file will be printed to the console only if you have permission to read the file. If you pass an invalid file, the node will throw an error object.
Conclusion
Node.js has a module file system that has methods readFile() and readFileSync() to read files. readFile() method read file asynchronously and readFileSync() method read file synchronously. Asynchronously means non-blocking, i.e., it does not block the execution of other programs, whereas synchronously means blocking, i.e., blocking other programs until execution is complete.
Reference
https://nodejs.org/api/fs.html#fsreadfilepath-options-callback