Nodejs-Built-in-FS-Modules

 

Built-in Modules

These are the native modules that come with Node.js. To use built-in modules, you need not install with npm or other package managers, all you have to do is to require(import) the native module you want to use. There are a lot of these built-in node modules. I will just state and describe a few of them that are often used for development of most applications.

  • fs - used to handle file systems.
  • http or https - for creating HTTP(S) servers
  • events - used to handle events.
  • util - used to handle utility functions e.g deprecate, inspect and format.
  • buffer - used to handle binary data.
  • stream - used to handle streaming data.
  • path - provides utilities for working with file and directory paths. To check out the list of all the other Node.js core modules, check out the official documentation here.

fs -(file system) module in Node.js is a built-in module that provides an interface for interacting with the tile system. It allows you to perform various file operations, such as reading from and writing to files, and creating and deleting directories,.
  • Create a Folder or File
  • Read Files
  • Renaming Files
  • Deleting Files

Using Reading File, u need to create a demo.txt file with some text, then use this code..

const fs = require('fs');

fs.readFile('demo.txt','utf-8',(err,data)=>{
    if(err){
        console.log(err);
    }
    console.log(data);

})

Using WriteFile, u need to create an example.html file with some text, then use this code...

const fs = require('fs');
fs.writeFile('example.html','utf8',(err)=>{
    if(err){
        console.log(err)
    }
    console.log('file created successfully');
}) Using rename, u need to create an example.html file with some text, then use this code...

const fs = require('fs');

fs.rename('example.html','newChangedFile.js',(err)=>{
    if(err){
        console.log(err)
    }else{
        console.log("File content is successfully changed")
    }
})
Using unlink- to delete the file, u need to define the name of the deleting file,
here I would like to delete newChangedFile.js 

const fs = require('fs');

fs.unlink('newChangedFile.js',(err)=>{
    if(err){
        console.log(err)
    }else{
        console.log("File deleted success")
    }
})