Node.js Tutorial --Reading and Writing files

in GEMS4 years ago

Hello Everyone

Today in this post we are going to learn a node module that will help us read and write a file through a simple script. This Module will help us in the upcoming tutorials because we are going to create some useful Hive tools. So without wasting time let's begin.

  • First of all, we need the Node.js installed. If you don't have Node.js installed. Install it by visiting its official page to download the package according to your operating system. As I already have Node.js installed so I will skip this step.

  • Another piece of software you need is a plain text editor. I am using a Subline text editor. You can use other editors like subline, Atom, etc.

  • Open the VS code/Subline ...

  • open the folder where you want to keep the files. If you have Git installed bash on the folder and type touch index.js to create a new .js file. If you don't have git just create a file and name it .js.

  • now include the fs module.

image.png

Let's say I want to create a .txt file and store some text in that file.

image.png

Open a command prompt or git to run the script.

image.png

This will not print anything console because it is sync and does not contain a call back function.

image.png
We have created the file and stored the text in it. ( The file wasn't there before);

  • Now let's access the same file through fs. We will read the same file using the fs.readFile.

image.png

This time we are storing the text from the file in a variable and then show the text on the console.

image.png

Now let's use a call back function while writing a file because we are getting any error or success message while executing.

image.png

Now If the code able to create and edit file it will display a message done editing else if it catch some error it will throw that error.

image.png


I think this much is enough for today. Now if you like the post please upvote and comment if you want to give me some advise
ntitled-1.png

Sort:  

Congratulations @pakgamer! You have completed the following achievement on the Hive blockchain and have been rewarded with new badge(s) :

You received more than 3250 upvotes. Your next target is to reach 3500 upvotes.

You can view your badges on your board And compare to others on the Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

To support your work, I also upvoted your post!

Do not miss the last post from @hivebuzz:

Hive Whale - Make it spray and get your badge!
Support the HiveBuzz project. Vote for our proposal!