Most Popular Tutorials
Most Popular Tutorials :-

Simply Easy Learning at Your Fingertips. Click Tutorials Menu to view More Tutorial List





File module in node.js

Node.js helps developers to write JavaScript code to run on the server-side, to generate dynamic content and deliver to the web clients.

file system

In File system handle file operations like creating, reading, deleting, etc.

Node.js provides an inbuilt module called FS (File System).

include the File System module, use the require() method:

Node.js includes fs module to access physical file system. The fs module is responsible for all the asynchronous or synchronous file I/O operations.

File Name :

var fs = require('fs');

Common use for the File System module:

File Name :

  • Read files
  • Create files
  • Update files
  • Delete files
  • Rename files

  • Read Files

    The fs.readFile() method is used to read files.

    File Name : index.php

    <html>
    <body>
    <h1>ittutorial</h1>
    <p>NodeJs Tutorial</p>
    </body>
    </html>

    File Name : myfile.js

    var http = require('http');
    var fs = require('fs');
    http.createServer(function (req, res) {
    //Open a file on the server and return its content:
    fs.readFile('index.php', function(err, data) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(data);
    return res.end();
    });
    }).listen(8080);

    Create Files

    The File System module has methods for creating new files:

  • fs.appendFile()
  • fs.open()
  • fs.writeFile()

  • The fs.appendFile() method appends specified content to a file. If the file does not exist, the file will be created:

    File Name :

    var fs = require('fs');

    //create a file named newfile.txt:
    fs.appendFile('newfile.txt', 'Hello Sana!', function (err) {
    if (err) throw err;
    console.log('Saved!');
    });

    fs.open()

    fs.open(path, flags, mode, callback)

    Parameters:

    path: It holds the name of the file to read or the entire path if stored at other locations.
    flags: Flags indicate the behavior of the file to be opened. All possible values are ( r, r+, rs, rs+, w, wx, w+, wx+, a, ax, a+, ax+).
    mode: Sets the mode of file i.e. r-read, w-write, r+ -readwrite. It sets to default as readwrite.
    callback:
    It is a callback function that is called after reading a file. It takes two parameters:

    err: If any error occurs.
    data: Contents of the file. It is called after the open operation is executed.

    File Name :

    var fs = require('fs');

    //create an empty file named newfile.txt:
    fs.open('newfile.txt', 'w', function (err, file) {
    if (err) throw err;
    console.log('Saved!');
    });

    fs.writeFile()

    File Name :

    var fs = require('fs');

    //create a file named newfile.txt:
    fs.writeFile('newfile.txt', 'Hello Sana!', function (err) {
    if (err) throw err;
    console.log('Saved!');
    });

    Update Files

  • fs.appendFile()
  • fs.writeFile()
  • File Name :


    Delete Files

    To delete a file with the File System module, use the fs.unlink() method.

    File Name :

    var fs = require('fs');

    //Delete the file mynewfile2.txt:
    fs.unlink('mynewfile2.txt', function (err) {
    if (err) throw err;
    console.log('File deleted!');
    });


    var fs = require("fs");

    console.log("deleting an existing file");
    fs.unlink('input.txt', function(err) {
    if (err) {
    return console.error(err);
    }
    console.log("File deleted successfully!");
    });

    Rename Files

    To rename a file with the File System module, use the fs.rename() method.

    File Name :

    var fs = require('fs');

    //Rename the file "mynewfile1.txt" into "myrenamedfile.txt":
    fs.rename('mynewfile1.txt', 'myrenamedfile.txt', function (err) {
    if (err) throw err;
    console.log('File Renamed!');
    });

    Reading File:

    File Name :

    Reading a File: The fs.read() method is used to read the file specified by fd. This method reads the entire file into the buffer.

    Syntax:

    fs.read(fd, buffer, offset, length, position, callback)
    Parameters:

    fd: This is the file descriptor returned by fs.open() method.
    buffer: This is the buffer that the data will be written to.
    offset: This is the offset in the buffer to start writing at.
    length: This is an integer specifying the number of bytes to read.
    position: This is an integer specifying where to begin reading from in the file. If the position is null, data will be read from the current file position.
    callback: It is a callback function that is called after reading of the file. It takes two parameters:
    err: If any error occurs.
    data: Contents of the file.

    File Name :

    var fs = require("fs");
    var buf = new Buffer(1024);

    console.log("opening an existing file");
    fs.open('input.txt', 'r+', function(err, fd) {
    if (err) {
    return console.error(err);
    }
    console.log("File opened successfully!");
    console.log("reading the file");

    fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){
    if (err){
    console.log(err);
    }
    console.log(bytes + " bytes read");

    // Print only read bytes to avoid junk.
    if(bytes > 0){
    console.log(buf.slice(0, bytes).toString());
    }
    });
    });

    Create Directory dynamically

    File Name :

    const dirPath = path.join(__dirname, '/public/images');
    console.log(dirPath);
    // fs.mkdirSync(dirPath); // it create directory in this path
    if (!fs.existsSync(dirPath)) {
    fs.mkdirSync(dirPath);
    console.log("folder created");

    }
    else{
    console.log("folder exists");
    }

    // fs.openSync(dirPath, 'hello.jpeg');

    const url = dirPath+'/resume-1662011752776.jpg';
    console.log(url);

    const filename = path.basename(url);
    console.log(filename);

    How to check file exist or Not?

    In NodeJS, You can check if a certain file exists your filesystem by using the file system module.

    const fs = require("fs");

    File Name :


    There are four methods that you can use to check if a certain file or folder exists inside the fs module:

  • fs.existsSync()
  • fs.exists()
  • fs.accessSync()
  • fs.access()
  • fs.existsSync()

    The fs.existsSync() method allows you to check for the existence of a file by tracing if a specified path can be accessed from the current directory where the script is executed. It returns true when the path exists and false when it’s not.

    The fs.existsSync() is a synchronous method, which means it stops the execution of JavaScript code until the method finish its process

    File Name :

    const fs = require("fs");
    const path = "./index.html";
    if (fs.existsSync(path)) {
    // path exists
    console.log("exists:", path);
    } else {
    console.log("DOES NOT exist:", path);
    }

    The existsSync() method can also check for the existence of a folder.

    File Name :

    const fs = require("fs");
    const path = "./assets";
    if (fs.existsSync(path)) {
    // path exists
    console.log("exists:", path);
    } else {
    console.log("DOES NOT exist:", path);
    }

    Checking file existence with exists() method

    File Name :

    const fs = require("fs");
    const path = "./index.php";
    fs.exists(path, function (isExist) {
    if (isExist) {
    console.log("exists:", path);
    } else {
    console.log("DOES NOT exist:", path);
    }
    });

    Checking file existence with accessSync()

    File Name :

    const fs = require("fs");
    const path = "./file.txt";
    try {
    fs.accessSync(path);
    console.log("exists:", path);
    } catch (err) {
    console.log("DOES NOT exist:", path);
    console.error(err);
    }

    Checking file existence with access()

    File Name :

    const fs = require("fs");
    const path = "./file.txt";
    fs.access(path, function (error) {
    if (error) {
    console.log("DOES NOT exist:", path);
    console.error(error);
    } else {
    console.log("exists:", path);
    }
    });





    Previous Next


    Trending Tutorials




    Review & Rating

    0.0 / 5

    0 Review

    5
    (0)

    4
    (0)

    3
    (0)

    2
    (0)

    1
    (0)

    Write Review Here