JavaScript Journal: Reading Local Files in Node.js (Part 1).


Prerequisite Knowledge:
JavaScript Fundamentals.
Programming Modules.
Unlike Python and Java, JavaScript lacks a simple read() method that helps the program read content from a local file. Its approach to this problem is a set of less simpler steps compared to the direct and concise way in some other languages.
Node.js, a runtime environment for traditional JavaScript, is also characterized by this feature. This is partly because JavaScript was initially created as a light-weight language to add dynamism to static webpages(
Concepts of Programming Languages by Robert W Sebasta
)
. As it evolved to a well-structured dialect with support, it was necessary to ensure its implementation remained efficient and Non-blocking.
When a program operation is Blocking, other executions are suspended until the operation completes. The program cannot do anything else while it is waiting for the blocking operation to finish.
However, Node.js contains a set of tools embedded in the File System(fs) module, which, when imported into the program, can be used to read local files. These are:
The fs.readFileSync() method.
The fs.readFile() method.
1. fs.readFileSync()
This approach, though a blocking approach, otherwise known as Synchronous Programming, is a less complex way of reading files into the program. When imported from the fs module;
It halts the rest of the program,
reads the content in the local file, and
copies it into a program variable, then.
continues to execute other parts of the program.
Here is a simple code snippet to show its implementation.
//The next line imports the file system(fs) module
const fs = require(“fs”);
/*The next line uses the readFileSync() method from the imported module to read the file, taking file name and file encoding as inputs.
*/const myFile = fs.readFileSync(“localfile.txt”, “utf8”);
//finally, the last line prints the contents of the file on the console
console.log(myFile);
2. fs.readFile()
The fs.readFile() method, on the other hand, executes this same task differently. While it doesn’t interrupt the rest of the program, it reads the contents of the file in the background and returns the file’s content when it’s ready. This form of program execution is also called asynchronous programming. The operation:
Imports the fs module into the program
Runs the fs.readFile() operation with file path, file encoding, and a callback function as parameters.
Returns the contents of the file using the callback function.
Here is another code snippet for the program’s implementation.
//the next line imports the file system(fs) module
const fs = require('fs');
/*The next block of code contains the readFile() operation and the callback function. The fs.readFile() method takes the file path, file encoding and callback function as parameters, while the callback function takes a variable to store the contents of the file and an err message— incase, the file is not found- as parameters*/
fs.readFile('myfile.txt', 'utf8', (err, data) => {
if (err) {
console.error('Error reading the file:', err.message);
return;
}
// Output the content to the console
console.log(data);
});
Though the fs.readFile() method is a more efficient algorithm for reading files, the contents of the files can only be used within the function scope. To bypass this roadblock, Node.js provides numerous methods to enable the utilization of file contents in other parts of the program. These are:
Use a Callback Function
Use Promises with
.then()
Use
async/await
To further understand how these methods work, do check out the second part of this article that explores Asynchronous Programming and the fs.readFile() method.
Subscribe to my newsletter
Read articles from Ugoaneni Victor directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Ugoaneni Victor
Ugoaneni Victor
A final year Computer Science Student with strong interest in Computer Networks, Machine Learning, and Language Implementation.