Menu BAR

FEEL FREE TO ASK ANY PROGRAM and please mention any error if you find it

6 Feb 2024

NODE JS BUILT-IN MODULE - FS

 1) What does FS module do?


1) The Node fs module provides functions for interacting with the file system on your computer.

2) It allows you to perform various operations such as reading from and writing to the files, creating and deleting files/folders, and much more.

3) Importing the 'fs' module:
var fs = require('fs');

Examples of various operations are below:

2) Reading from a file

fs.readFile('example.txt', 'utf8', (err, data) => {
         if (err) { 
                console.error(err); 
                return; 
               
        console.log(data); 
});

3) Creating a new file

There are three ways to create a new file using the fs module-

1) Using appendFile() method -  This method appends specified content to a file. If the file does not exist, a new file will be created.

fs.appendFile('mynewfile1.txt', 'Hello content!', function (err) { 
        if (err) 
                throw err; 
        console.log('Saved!'); 
});

2) Using the open() method - This method opens the specified file for writing if the flag (second argument) is passed as w which means writing. If the file does not exist, a new file will be created.

fs.open('mynewfile2.txt', 'w', function (err, file) { 
        if (err) 
                throw err; 
        console.log('Saved!'); 
});

3) Using the writeFile() method - This method replaces the specified file and content if it exists. If the file does not exist, a new file will be created.

fs.writeFile('mynewfile3.txt', 'Hello content!', function (err) { 
        if (err) 
                throw err; 
        console.log('Saved!'); 
});

4) Deleting a File

The fs.unlink() method deletes the specified file.

fs.unlink('myfile.txt', function (err) { 
        if (err) 
                throw err; 
        console.log('File deleted!'); 
});


No comments:

Post a Comment