Node.js: Read File Using Fs

Introduction

So, we are in Node.js and this article shows to write a script using the file-system module of node.js. In between, we will compare the code of PHP and node.js that can be used as alternatives.

And, yes node is easy and fluent as compared to PHP. As we know, node is designed to fulfill some sort of task and it does those jobs with Excellency.

Background

In background, we will use JavaScript as the language with the node.js framework. Inclusively, we will use the file system module in node.js.

When you look at the node.js documentation you will find the file system module.

system module

There you will find several functions and we will use one of them.

Code

Code

So, start from the first line of code.

fs is a variable for storing a reference of the file-system. In JavaScript we use the require() function to include an external module.

Then, we need a callback function that will show your text-file content. So, it takes two arguments, error and data. Where data is your content. Thus, we haved used the console.log() function to show your content.

And, next we have the readFile() function that takes two arguments. First will be your resource-file's path and the second will be your callback function.

And finally, we have written another print statement so that we can see the non-block nature of node.

Before, we move to the explanation part.

Output

move in explanation

As we can see, "Continue…" is in the beginning and then we have the contents of the text file. That is just because, node starts executing the code and when it gets to the readFile() function it doesn't stop there, else it moves to the next statement (non-blocking state) and when reading is completed it gets called to print the output. That's why, we call those function as callback functions.

And, to make it more precise, we can write it as:

readFile

It's a more precise and common way to write a callback function.

To do the same job, we have a PHP script that is something like this:

PHP script

But, this is synchronous in nature and follows the conventional methodology.

Conclusion

It's a basic step toward node and in a future series of articles we will learn some new ways to do odd jobs with node framework.

For any confusion, you can refer to the attachment.


Similar Articles