How To Read A File Using Node.js (Part 1)

A: Intro

How To Read A File Using Node.js (Part 1) –>  While learning Node.js, I noticed that the File System module was being used in many of the examples that I had seen. Thus, I decided to share what I’d learned. Particularly, how to read a file in Node.js using the File System module.

It’s worth mentioning, before we begin, that the fs module has two primary methods to read a file–the .readFile() method and the .readFileSync() method. The main difference between the two is the blocking and non-blocking I/O principle that either requires a callback or doesn’t. More on that later. However, for now, within this post we’ll look at the .readFile() method.

Installing Node.js

To begin, make sure that you have Node.js installed. If you don’t, this tutorial may help with the installation process. If not, I have a created video that walks you step by step in installing it.

B: Begin

1. Create a directory

First off,  create a directory called Node app and add a file called app.js to it.

How To Read A File Using Node.js (Part 1)
Node app directory with app.js inside

2. Require File System

Now, to access the File System in Node.js we’ll need to require it using the .require() function and assign it to a variable. In this case, a constanst called fs.

const fs = require('fs');

3. Create hello.txt file

Next, we’ll create a file called hello.txt and add some text in it.

How To Read A File Using Node.js (Part 1)
hello.txt file in Node app directory
How To Read A File Using Node.js (Part 1)
Text added to hello.txt file

4. Using the .readFile() method

After we’ve created hello.txt, we’ll attach .readFile() to the fs variable and add it as an argument.

fs.readFile("hello.txt");

5. Run app.js in the terminal

At this point, within the Node app directory, if we run that app in the terminal we’ll receive the following message.

jesushilariohernandez$ node app.js
fs.js:159
  throw new ERR_INVALID_CALLBACK();
  ^

TypeError [ERR_INVALID_CALLBACK]: Callback must be a function
    at maybeCallback (fs.js:159:9)
    at Object.fs.readFile (fs.js:275:14)
    at Object. (/Users/jesushilariohernandez/Desktop/node apps/Node app/app.js:3:4)
    at Module._compile (internal/modules/cjs/loader.js:702:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:713:10)
    at Module.load (internal/modules/cjs/loader.js:612:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:551:12)
    at Function.Module._load (internal/modules/cjs/loader.js:543:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:744:10)
    at startup (internal/bootstrap/node.js:238:19)

Note that the portion directly at the beginning of the error is most significant when trying to figure out where the error has occurred.

6. Adding a callback

Given that .readFile() is an asynchronous method, we are probably going to need to pass in a callback function as argument.

fs.readFile("hello.txt", () => {

});

Here, I’ve used the ES6 arrow function as a callback argument. However, we could have used the traditional javascript function in it’s place. No problem.

fs.readFile("hello.txt", function() {

});

In any case, it’s probably best to learn that both. I’m sure there’s lots of code out there that still uses the traditional javascript function syntax.

7. Adding callback arguments

Now that we have our callback in place, we need to pass in two argument–error and data. Node.js will store an error message, if any, inside of the error argument and the text file data into the data argument.

fs.readFile("hello.txt", (error, data) => {

});

Beautiful, let’s console.log() the data.

fs.readFile("hello.txt", (error, data) => {
  console.log(data);
});

Swell, let’s take is a step further and throw in an if else statement, should an error occur.

fs.readFile("hello.txt", (error, data) => {
    if (error) throw error 
    else console.log(data);
});

8. Run app.js

jesushilariohernandez$ node app.js

After running the app, we get this response:

jesushilariohernandez$ node app.js
<Buffer 48 65 6c 6c 6f 0a 48 6f 6c 61 0a 48 65 6c 6c 6f 0a d0 97 d0 b4 d1 80 d0 b0 
d0 b2 d1 81 d1 82 d0 b2 d1 83 d0 b9 d1 82 d0 b5 0a 48 61 6c 6c 6f 0a 43 69 ... >

Great, while this looks like an error, it’s actually not! This is a good sign!  What we’re looking at is the Buffer response of our text. To fix this, we’ll need to encode the text in order to read it as we see it in the text file.

9. Encoding the data response

To encode, we’ll need to pass the options argument as a string into the callback function.

fs.readFile("hello.txt", "UTF-8", (error, data) => { 
    if (error) throw error; 
    else console.log(data); 
});

Cool, once we run the app we’ll see our intended response.

10. Run app.js again

jesushilariohernandez$ node app.js
Hello
Hola
Hello
Здравствуйте
Hallo
Ciao
Bonjour
Kamusta

Yes! That’s it! We have successfully read a file in Node.js.

C: Outro

So, to recap, we’ve successfully read a file in Node.js using File System’s .readFile() method. The .readFile() method, as we remember, is an async method that takes in three arguments: file path (hello.txt), options  (encoding type), and a callback. And that in order to get our data from the file, we needed to pass in arguments error and data within the callback function. Once the method syntax was complete, we then needed to print the data from our hello.txt file. We did this by putting our error and data variables into an if else block in case an error should occur.

Full Code Here

const fs = require('fs');

fs.readFile("hello.txt", "UTF-8", (error, data) => {
  if (error) throw error;
  else console.log(data);
});

Leave a Reply