Empowering you to understand your world

Node.js Tutorials: How To Read A File In Node.js

By Nicholas Brown – Follow me on X.

You can read a file using Node.js with the FS library. For this tutorial, we will use the FS library to read a JSON file and parse its contents. Configuration files are widely used in applications as a simple, quick way to store and retrieve settings and other things that need to persist between app uses.

You can use the same code samples below to store regular text in files. You would only need to remove the ‘JSON.parse’ and ‘.Language’ lines.

Example Code: How To Read A File Asynchronously 

You can read a file using Node.js to prevent the file operation from blocking other activities in your application. It will continue to execute on the back burner while your website or app loads quickly. This is called an asynchronous file operation.

This code sample reads a JSON object from a JSON file and stores it in a variable.

const file = require('fs');  //Add the FS module to the app and create an object called 'file'.

file.readFile('config.json', 'utf8', (error, data) => { //Read the file into the 'data' variable.
if (error) { console.log(error); } else { let jsondata = JSON.parse(data); //Parse the JSON data from the file so we can access its fields properly.
console.log(jsondata); //Print the file contents to the console.
console.log(jsondata.Language); //Access only the 'Language' field. } });

After the file is read into the ‘data‘ variable, it is parsed and the parsed data is stored in the ‘jsondata‘ variable. Parsing it enables us to access the fields of the JSON object. To access a specific field in the JSON object, just type ‘variablename.fieldname’.

The console output should look like this:

Example Code: How To Do It Synchronously

If you need to ensure that your file is read before your app continues execution, you can do so by reading your file synchronously as shown below. The same example configuration file is used for the following code sample.

const file = require('fs');

try {
let data = file.readFileSync('config.json', 'utf8'); //No callback required.
let jsondata = JSON.parse(data);
console.log(jsondata);
console.log(jsondata.Language);
} catch(error) {
console.log(error);
}

Further Reading

How To Send A Post Request Using Node.js

How To Send A GET Request From An iOS App (Swift)

Leave a Reply

Subscribe to our newsletter
Get notified when new content is published