Node Js Tutorial Read , Write and Edit files and directories by fs module
What Will I Learn?
I will learn in thistutorial how to read , write and edit the files and directories using the fs library .
- How to read and write the files synchronously and asynchronous .
- How to edit files by the method replace in a new variable .
- How to create directory and remove it by the 'mkdir ' and 'rmdir ' methods .
Requirements
- Node JS must be installed on your device , you can install it From here
- Knowledge about JavaScript language .
- Basic Knowledge about Command Line window .
- An editor for example notepad ++ .
Difficulty
- Basic
Tutorial Contents
In this tutorial I am going to talk about reading , writing and editing files in Node Js also manage directories by add and delete , let's start ..
Read File in Node Js :
This action is very important for you as programmer , in many times we need to read the content of another file with another extension to get the content and to manipulate , apply it in a condition or print it ..etc
To use the read file you must firstly get the ' fs ' module by the ' require ' I explained before what's the module , in this library we can find the actions that I will explain right now .
var fs = require('fs')
I have created a variable named for example ' fs ' it's equals to the library ' fs ' to give us the possibility to use the read file , then we have two types of reading :
1- Read File Synchronously :
The term ' synchronously ' in different languages means this action will block all the instructions after it , it will firstly excute the ' read file ' After completion the node will continue to excute the rest , it's difficult to understand , let's do an example :
I have a txt file named terms inside it I have a content of ' terms of use ' the idea is to print the content of the file to the user for that I want to use the ' readFileSync ' after read and print the content I will print also by ' console.log ' the word ' accept or refuse ' to be logically and to understand more the difference between them .
This is the content of my file , after the first code ' require('fs') ' I will now read the file by this code :
var terms = fs.readFileSync('terms.txt', 'utf8')
I have created another variable named terms the value of this variable is the content of my file but how to get it ? simply by ' readFileSync ' if you look at this method is 'Sync ' is means synchronously , it has two parameters the first is the name of our file with the extension and the second is the encoding , in this example I used the ' utf8 ' encoding there is many types depend to the content of your file for example ' US-ASCII or UTF-32 ..etc ' you can read about them on WIKIPEDIA , then I want to print the variable that has the content of my file by the console log
console.log(terms);
After that I want to print the word ' accept or refuse ' to see if it block really the code or what will happen ..
console.log('Accept Or Refus ');
This is all the code :
I want now to excute this method on my command line I will type node pro
when pro is my node js file and this is the result
So I have firstly the terms of use then I have the message accept or refuse for example , and this is the meaning of synchronously .
2- Read File Asynchronously :
I will do the same example but with the method ' readFile ' without ' Sync ' to be asynchronously non blocking action I will firstly get the module ' fs ' by the require('fs') , then I will apply this method like it :
fs.readFile('terms.txt', 'utf8', function(err, data){
console.log(data)
});
This method get 3 parameters , the first is the name of our file the second is the encoding type as I mentioned above the third parameter is a function . This function is going to be called when the file-reading operation has finished .
The function has two parameters the first is an error if there is an error in the operation and the second is the data or the content of the file , inside it I used the console log to print the content the data of the file .
To test if it's blocking or non-blocking operation I will add after the method another message to print ' accept or Refuse '
console.log('Accept Or Refus ');
This is all the code :
And this is the result to understand exactly what's the difference between them :
The ' accept or refuse ' before the terms of use despite I have written the method readFile before but because it's non-blocking operation the node has executed and print the word ' accept or refuse ' before reading the file and this is the difference between the ' readFileSync ' and ' readFile ' methods .
Write File in Node Js :
You can by node js controle the files by reading and writing files , really it's an advantage that node js gives .
The same idea we have two types of writing synchronously and asynchronous , as I mentioned above the first will block all the code after it , but the second is non blocking .
Write File Synchronously :
I will create a new file , my idea is to create a copy from terms.txt after reading I will make the content of this file into the terms variable and create the file with the value exists on the variable and this is the code
var fs = require('fs');
var terms = fs.readFileSync('terms.txt', 'utf8');
fs.writeFileSync('copy.txt', terms);
console.log('You have created a copy from terms ');
I used the method ' writeFileSync ' the first parameter is the name of the file that you want to create and the second is the content of your file for me in this example I took the content into the variable terms which is the terms of use and this is the result of my copy file :
The same content on my copy file , sure the file was created after I excuted it on node js by this code
Write File Asynchronous:
The same thing as the reading operation it's a non-blocking operation and for that I want to create a copy file with the content of terms of use :
var fs = require('fs');
var terms = fs.readFileSync('terms.txt', 'utf8');
fs.writeFile('copy.txt', terms, function(err, data){
console.log('The terms are on this file');
});
console.log('You have created a copy from terms ');
So a third parameter is a function has two parameters this function will execute when the operation has finished it will print ' the terms are on this file ' and the second instruction will print ' You have created a copy from terms ' and we will see the result any sentence will be the first to understand more the blocking operation ..
Edit File in Node Js :
Sometimes you want to create a file copy from another file but with some changes for that node JS give us the possibility to modify the content of the files for that I want to read the terms and change the age from 19 years to 20 and create the copy file and this is the code :
var fs = require('fs');
fs.readFile('terms.txt', 'utf8', function(err, data){
var newValue = data.replace('19', '20');
fs.writeFile('copy.txt', newValue, function(){
console.log(newValue);
});
});
console.log('You have modified the file ');
Firstly I read the file terms.txt and inside the function and after the operation I will create a new value as a variable inside this new value I will change the data or the content of the file and replace the value 19 to 20 by the method ' replace ' with two parameter the old value and the new value , after that I will create the new file named copy with the extension txt with the new value and a function to print the content of my new file , finally a message to know that we have modified the value and this is the result
Now before I start explaining the directories I want to explain how to remove the file copy.txt that we created for that I am going to use the ' unlink() ' method in the ' fs ' library and this is the code
var fs = require('fs');
fs.unlink('copy.txt');
console.log('You have Deleted This file ');
This method has as parameter the name of the file that you want to delete on condition it will be in the same directory of your current file and this is the result :
The file was deleted but be curfel if you restart this file again you will get an error because there is no file in this directory named copy.txt and this is the error
And for that we will explain the directories ..
Directories :
1 - Create Directory :
To organize the files we need directories for exmaple in WordPress we have a directory of themes inside it we find another directories of themes each one is a theme has some files and I will do an example of themes , firstly I need to create two directories ' theme 1 ' and ' theme 2 ' and this is the code
fs.mkdirSync('theme1');
fs.mkdirSync('theme2');
Always with the same module ' fs ' I have this method ' mkdirSync ' synchronously and I have explained it , it has as parameter the name of my directory , so I created two directories then I want to create two files each one inside a theme , let's do it
fs.mkdir('theme1', function(){
fs.readFile('content1.txt', 'utf8', function(err, data){
fs.writeFileSync('./theme1/copyContent1.txt', data);
});
});
fs.mkdir('theme2', function(){
fs.readFile('content2.txt', 'utf8', function(err, data){
fs.writeFileSync('./theme2/copyContent2.txt', data);
});
});
So I have used the 'mkdir ' method without ' Sync ' and when it's asynchronous method it should have a function , when the operation finished it will read the content1 file and write a new copyfile inside the './theme1 ' directory , it means in the same way in the directory theme1 .
The same thing for the second directory I will create a copy from content2 inside the function of the directory , after the two operations a message will be displayed console.log('You have created the new directories ');
and this is the result :
2 - Remove Directory :
To remove a directory that you have created for example of something in your system , you must use ' rm ' at place of ' mk ' it will be ' rmdir ' and this is the code fs.rmdir('theme1');
and this is the full code
var fs = require('fs');
fs.rmdir('theme1');
console.log('You have deleted this directory ');
You can combine between the ' unlink ' and ' rmdir ' to delete firstly the files then the directory but be careful in the unlink method you must specify the directory of the file ' ./theme1/content1.txt ' this is the directory .
Curriculum
Posted on Utopian.io - Rewarding Open Source Contributors
Thank you for the contribution. It has been approved.
You can contact us on Discord.
[utopian-moderator]
Thank you sir
Hey @alexendre-maxim I am @utopian-io. I have just upvoted you!
Achievements
Community-Driven Witness!
I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!
Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x
thank you
Congratulations @alexendre-maxim! You have completed some achievement on Steemit and have been rewarded with new badge(s) :
Click on any badge to view your own Board of Honor on SteemitBoard.
For more information about SteemitBoard, click here
If you no longer want to receive notifications, reply to this comment with the word
STOP