top

Search

Node JS Tutorial

Node.js has a module called FS to interact with the file system. This module will help to list files in a directory, create new files, modify files and delete the file as well. Along with we can watch and stream the file. Let’s go about this module with certain examples.  Note: File system related actions done in async are taken care of by libuv library. List directory files: App1:  Open IDE and Navigate to the folder in the terminal which has a folder with few images in it. Create list.js file inside the folder sibling to the images folder. Open list.js file and import the fs module. const fs = require(“fs”); console log that we have started reads the files. console.log(“started reading files”) fs has a method readdirSync with the parameter as a folder to read. const files = fs.readdirSync(“./images”); Here we are giving the relative path of the folder to read from Console log the files obtained with a message saying reading completed console.log(“completed reading files”); console.log(files); Run node list to view the output with the image files. App2: Reading directory files in async Currently, the readdirSync is synchronous and is a blocking operation. To have an async approach and non-blocking main thread while reading files, we can use readdir method. This is async in nature with a callback being called on completion of reading files. fs.readdir(“./images”, (err, files) =>{ if (err) { throw err; } console.log(“complete”) console.log(files); Since it is async and doesn’t return, we are logging the files read in callback. Also observe that if there is any error during reading of files, we are raising an error. Run node list and output should be the same.  Just that we are reading the files in async. constfs = require("fs");  fs.readdir("./images", (err, files) => {  if (err) {  throwerr;    }  console.log("complete");  console.log(files);  });  console.log("started reading files"); Read files App1:  Create a file with name data.txt from which we need to read the data. Create a readFile.js and import the fileSystem module. const fs = require(“fs”); We have a version of readFile in fs, one for sync and another for async. Lets do sync way const text = fs.readFileSync(“./data.txt”, “UTF-8”) // since it is a text file we are reading as UTF-8 format. console.log(text); Similarly in async way. fs.readFile(“./data.txt”,”UTF-8”, (err, data) => { if (err)  {  console.log(`error occurred while reading file: ${err}’);  process.exit();  }  console.log(“file content is read”)  console.log(data);  ); Note: While reading binary files like images, we don’t supply the encoding format i.e. UTF-8. Write and append files App1: Create writeFile.js and import fs module const fs = require(“fs”); const content = ` This is a new file created using fs module` fs.writeFile(“./newfile.txt”, content, (err) => { if (err) { throw err; }  console.log(“file has been created successfully”);  ); run node writeFile.js and observe that file is created App2:  Create an appendFile.js and import fs module Instead of writing the content, lets read the content from one file and append to another file. Create two files, one for appending (newAppendFile.txt) and another for reading the content (dataFile.json). const fs = require(“fs”); const dataFile = require(“./dataFile”); fs.appendFile(“./newAppendFile.txt”, dataFile, (err) => {    if (err) { throw err; }  }); Here we are reading the entire content and appending to the file. If the appending file doesn’t exist then it will create and for later on it will append. We can parse the content of dataFile to append specific content using javascript methods. Directory creation App1:  create directory.js and import fs module const fs = require(“fs”); fs.mkdir(“newFolder”, err => { if (err) { throw err; }  console.log(`Directory newFolder is created successfully`);  }); run node directory and navigate to folder directory to see new folder getting created. Try to re-run and see that error is thrown that directory already exists. To avoid this, let's add a condition to check if the directory exists. If (fs.existsSync(“newFolder”)) {       Console.log(“NewFolder already exists”);  } else {    Copy the line 3 code i.e. fs.mkdir(…);  } Now re-run node directory and observe that error is not thrown and says directory already exists. Rename and remove files App1:  Create a file rename.js and import fs. const fs = require(“fs”); Use renameSync to rename the file in synchronous way or  fs.renameSync(“./data.json”, “./newdata.json”); User rename directly to rename the file in async way. If the destination path is different then it is moved. fs.rename(“./newdata.json”, “./newFolder/newdata.json”, err => { if (err) { throw err; }  ); To remove, we can use unlinkSync or unlink in fs. We will do it in a setTimeout say after 2 seconds. setTimeout(()=> { fs.unlinksync(“./newFolder/newdata.json”); }, 2000); run node rename.js Observe that file has been rename and then moved. After moving post 2 seconds, see the file is getting deleted.  For better tracking, we can have different files as in the above example we are using the same file. For rename directories, we can use the same method rename. However, for removing we need to use rmdir. Before deleting a directory, it has to be empty. This implies that to remove directory we need to remove all the files and then remove the directory. constfs = require("fs");  fs.readdirSync("./deleteDirectory").forEach(fileName=> {  fs.unlinkSync(`./deleteDirectory/${fileName}`);  });  fs.rmdir("./deleteDirectory", err=> {  if (err) {  throwerr;    }  console.log("./deleteDirectory is removed");  });
logo

Node JS Tutorial

File System

Node.js has a module called FS to interact with the file system. This module will help to list files in a directory, create new files, modify files and delete the file as well. Along with we can watch and stream the file. Let’s go about this module with certain examples.  

Note: File system related actions done in async are taken care of by libuv library. 

List directory files: 

App1:  

  • Open IDE and Navigate to the folder in the terminal which has a folder with few images in it. 
  • Create list.js file inside the folder sibling to the images folder. 
  • Open list.js file and import the fs module. 
  • const fs = require(“fs”); 
  • console log that we have started reads the files. 
  • console.log(“started reading files”) 
  • fs has a method readdirSync with the parameter as a folder to read. 
  • const files = fs.readdirSync(“./images”); 
  • Here we are giving the relative path of the folder to read from 
  • Console log the files obtained with a message saying reading completed 
  • console.log(“completed reading files”); 
  • console.log(files); 
  • Run node list to view the output with the image files. 

App2: Reading directory files in async 

  • Currently, the readdirSync is synchronous and is a blocking operation. 
  • To have an async approach and non-blocking main thread while reading files, we can use readdir method. This is async in nature with a callback being called on completion of reading files. 
  • fs.readdir(“./images”, (err, files) =>{ 
  • if (err) { throw err; } 
  • console.log(“complete”) 
  • console.log(files); 
  • Since it is async and doesn’t return, we are logging the files read in callback. 
  • Also observe that if there is any error during reading of files, we are raising an error. 
  • Run node list and output should be the same.  Just that we are reading the files in async. 
constfs = require("fs"); 
fs.readdir("./images", (err, files) => { 
if (err) { 
throwerr; 
  } 
console.log("complete"); 
console.log(files); 
}); 
console.log("started reading files"); 

Read files 

App1:  

  • Create a file with name data.txt from which we need to read the data. 
  • Create a readFile.js and import the fileSystem module. 
  • const fs = require(“fs”); 
  • We have a version of readFile in fs, one for sync and another for async. 
  • Lets do sync way 
  • const text = fs.readFileSync(“./data.txt”, “UTF-8”) // since it is a text file we are reading as UTF-8 format. 
  • console.log(text); 
  • Similarly in async way. 
  • fs.readFile(“./data.txt”,”UTF-8”, (err, data) => { 
if (err)  { 
console.log(`error occurred while reading file: ${err}’); 
process.exit(); 
} 
console.log(“file content is read”) 
console.log(data); 
); 

Note: While reading binary files like images, we don’t supply the encoding format i.e. UTF-8. 

Write and append files 

App1: 

  • Create writeFile.js and import fs module 
  • const fs = require(“fs”); 
  • const content = ` This is a new file created using fs module` 
  • fs.writeFile(“./newfile.txt”, content, (err) => { 
if (err) { throw err; } 
console.log(“file has been created successfully”); 
); 
  • run node writeFile.js and observe that file is created 

App2:  

  • Create an appendFile.js and import fs module 
  • Instead of writing the content, lets read the content from one file and append to another file. 
  • Create two files, one for appending (newAppendFile.txt) and another for reading the content (dataFile.json). 
  • const fs = require(“fs”); 
  • const dataFile = require(“./dataFile”); 
  • fs.appendFile(“./newAppendFile.txt”, dataFile, (err) => { 
   if (err) { throw err; } 
}); 
  • Here we are reading the entire content and appending to the file. If the appending file doesn’t exist then it will create and for later on it will append. 
  • We can parse the content of dataFile to append specific content using javascript methods. 

Directory creation 

App1:  

  • create directory.js and import fs module 
  • const fs = require(“fs”); 
  • fs.mkdir(“newFolder”, err => {
if (err) { throw err; } 
console.log(`Directory newFolder is created successfully`); 
}); 
  • run node directory and navigate to folder directory to see new folder getting created. 
  • Try to re-run and see that error is thrown that directory already exists. 
  • To avoid this, let's add a condition to check if the directory exists. 
If (fs.existsSync(“newFolder”)) { 
     Console.log(“NewFolder already exists”); 
} else { 
  Copy the line 3 code i.e. fs.mkdir(…); 
} 
  • Now re-run node directory and observe that error is not thrown and says directory already exists. 

Rename and remove files 

App1:  

  • Create a file rename.js and import fs. 
  • const fs = require(“fs”); 
  • Use renameSync to rename the file in synchronous way or  
  • fs.renameSync(“./data.json”, “./newdata.json”); 
  • User rename directly to rename the file in async way. If the destination path is different then it is moved. 
  • fs.rename(“./newdata.json”, “./newFolder/newdata.json”, err => { 
if (err) { throw err; } 
); 
  • To remove, we can use unlinkSync or unlink in fs. We will do it in a setTimeout say after 2 seconds. 
  • setTimeout(()=> { fs.unlinksync(“./newFolder/newdata.json”); }, 2000); 
  • run node rename.js 
  • Observe that file has been rename and then moved. After moving post 2 seconds, see the file is getting deleted.  
  • For better tracking, we can have different files as in the above example we are using the same file. 

For rename directories, we can use the same method rename. However, for removing we need to use rmdir. Before deleting a directory, it has to be empty. This implies that to remove directory we need to remove all the files and then remove the directory. 

constfs = require("fs"); 
fs.readdirSync("./deleteDirectory").forEach(fileName=> { 
fs.unlinkSync(`./deleteDirectory/${fileName}`); 
}); 
fs.rmdir("./deleteDirectory", err=> { 
if (err) { 
throwerr; 
  } 
console.log("./deleteDirectory is removed"); 
}); 

Leave a Reply

Your email address will not be published. Required fields are marked *

Suggested Tutorials

JavaScript Tutorial

JavaScript is a dynamic computer programming language for the web. JavaScript was first known as LiveScript. Later on, Netscape changed its name to JavaScript because of its popularity and the excitement generated by it. JavaScript is lightweight and most commonly used as a part of web pages supported by most web browsers like Chrome, Internet Explorer, Opera, Safari, Edge, and Firefox.
JavaScript Tutorial

JavaScript is a dynamic computer programming language for the web. Jav...

Read More

Angular JS Tutorial

Introduction: Angular  (What is Angular?)Angular was formerly introduced by Google corporation in 2012 and was considered to be one of the most promising among JavaScript frameworks. It was written completely in JavaScript to separate an application’s logic from DOM manipulation, aiming at dynamic page updates. Angular introduced many powerful features enabling the developer to effortlessly create rich and single-page applications.Topics CoveredThis Angular tutorial will span over eight modules, each module covering numerous individual aspects that you need to gain complete information about Angular. This set of modules serves as an Angular tutorial for beginners along with experienced IT professionals.Here are the topics that will be covered in the Angular tutorial:Get started with Angular.Learn the basics of Angular.Know what Angular Directives.Get an idea of Component Inputs and Outputs of Angular.Know about Forms in Angular.About Services in Angular.Pipes in Angular.HTTP, Routing and Building in Angular.Who can benefit from this tutorial?This Angular tutorial will be helpful to IT professionals such as:Software Developers, Web Application Programmers and IT Professionals Software Architects and Testing Professionals Career aspirants in web development
Angular JS Tutorial

Introduction: Angular  (What is Angular?)Angular was formerly introdu...

Read More

USEFUL LINKS