NodeJS_Unit_5

File System

About Node.js file system:
• File System is big part of any application need to handle files for loading, manipulating or serving data.
• To handle file operations like creating, reading, deleting, etc., Node.js provides an inbuilt module called FS (File System).
• Node.js gives the functionality of file I/O by providing wrappers around the standard functions. All file system operations can have synchronous and asynchronous forms depending upon user requirements.
• To use this File System module, use the require() method:
var fs = require('fs');

What is Synchronous and Asynchronous approach?

Synchronous approach: They are called blocking functions as it waits for each operation to complete, only after that, it executes the next operation, hence blocking the next command from execution i.e. a command will not be executed until & unless the query has finished executing to get all the result from previous commands.
Asynchronous approach: They are called non-blocking functions as it never waits for each operation to complete, rather it executes all operations in the first go itself. The result of each operation will be handled once the result is available i.e. each command will be executed soon after the execution of the previous command. While the previous command runs in the background and loads the result once it is finished processing the data.

Fs.readFile

Read File Synchronously:

• The fs.readFileSync() method is an inbuilt application programming interface of fs module which is used to read the file and return its content.
• In fs.readFileSync() method, we can read files in a synchronous way, i.e. we are telling node.js to block other parallel process and do the current file reading process.

Syntax:
fs.readFileSync(path,options);

Parameters:
path: It takes the relative path of the text file.
options: It is an optional parameter which contains the encoding and flag, the encoding contains data specification.

Example:
    // Include fs module
    const fs = require ('fs');

    // Calling the readFileSync() method to read 'input.txt' file
    const data=fs.readFileSync('./input.txt',{encoding:'utf8',flag:'r'});

    // Display the file data
    console.log (data);

Read File Asynchronously:

To read content of a file into memory in Asynchronous way by using fs.readFile() method.
Syntax:
var fs=require (‘fs’);
fs.readFile (file, encoding, callback);

Parameters:
File: file path of the file or file name.
Encoding: Specifies the type of encoding to read the file. Types of encoding are ‘ascii’,’utf8’ and ‘base64’.
Callback: It is function to call when the file has been read the contents are ready.

Writing a File

• The ‘fs’ module of Node.js implements the File I/O operation. Methods in the fs module can be synchronous as well as asynchronous. The Asynchronous function has a callback function as the last parameter which indicates the completion of the asynchronous function.
• Node.js developers prefer asynchronous methods over synchronous methods as asynchronous methods never block a program during its execution.
• There are 2 ways to write in file Synchronously & Asynchronously.

Writing a file synchronously

• Synchronous functions should only be used for debugging or when no other options are available.
• The fs.writeFileSync() is a synchronous method.
• The fs.writeFileSync() creates a new file if the specified file does not exist.

Syntax:
fs.writeFileSync (file, data, options)

Parameters:
file: It is a string, Buffer, URL or file description that denotes the path of the file where it has to be written. Using a file descriptor will make the it behave similar to fs.write() method.
data: It is a string, Buffer, TypedArray or DataView that will be written to the file.
options: It is a string or object that can be used to specify optional parameters that will affect the output. It has three optional parameter:
o encoding: It is a string which specifies the encoding of the file. The default value is ‘utf8’.
o mode: It is an integer which specifies the file mode. The default value is 0o666.
o flag: It is a string which specifies the flag used while writing to the file. The default value is ‘w’.

Example:
    // Import the file system module
    const fs = require ('fs');

    let data = "This is a file containing a collection of programming languages.\n" + "1. C\n2. C++\n3. Python";

    fs.writeFileSync("programming.txt", data);
    console.log("File written successfully\n");
    console.log("The written has the following contents:");
    console.log(fs.readFileSync("programming.txt", "utf8"));


Writing a file asynchronously

The fs.writeFile() method is used to asynchronously write the specified data to a file.

Syntax:
fs.writeFile (file, data, options, callback);

Parameters:
file: It is a string, Buffer, URL or file description that denotes the path of the file where it has to be written. Using a file descriptor will make it behave similar to fs.write() method.
data: It is a string, Buffer, TypedArray or DataView that will be written to the file.
Options: It is a string or object that can be used to specify optional parameters that will affect the output. It has three optional parameter:
encoding: It is a string value that specifies the encoding of the file. The default value is ‘utf8’.
mode: It is an integer value that specifies the file mode. The default value is 0o666.
flag: It is a string value that specifies the flag used while writing to the file. The default value is ‘w’.
callback: It is the function that would be called when the method is executed.
err: It is an error that would be thrown if the operation fails.


Example:
    // Import the file system module
    const fs = require('fs');

    let data = "This is a file containing a collection of books.";

    fs.writeFile("books.txt", data, function(err)
    {
    if (err)
    console.log(err);
    else {
    console.log("File written successfully\n");
    console.log("The written has the following contents:");
    console.log(fs.readFileSync("books.txt", "utf8"));
    }
    });


Opening a file

• To create file, to write to a file or to read a file fs.open() method is used.
fs.readFile() is only for reading the file and similarly fs.writeFile() is only for writing to a file, whereas fs.open() method does several operations on a file.
• First we need to load the fs class which is module to access physical file system.

Syntax:
fs.open( filename, flags, mode, callback )

Parameter:
filename: It holds the name of the file to read or the entire path if stored at other location.
flag: The operation in which file has to be opened.
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: A file descriptor, used by subsequent file operations. A file descriptor is a handle used to access a file. It is a non-negative integer uniquely referencing a specific file.

Flag  Description
r To open file to read and throws exception if file doesn’t exists.
r+ Open file to read and write. Throws exception if file doesn’t exists.
rs+ Open file in synchronous mode to read and write.
w Open file for writing. File is created if it doesn’t exists.
wx It is same as ‘w’ but fails if path exists.
w+ Open file to read and write. File is created if it doesn’t exists.
wx+ It is same as ‘w+’ but fails if path exists.
a Open file to append. File is created if it doesn’t exists.
ax It is same as ‘a’ but fails if path exists.
a+ Open file for reading and appending. File is created if it doesn’t exists.
ax+ It is same as ‘a+’ but fails if path exists.


Example:
    // fs.open() Method
    var fs = require('fs');

    // Open file demo.txt in read mode
    fs.open('demo.txt', 'r', function (err) {
    console.log('Saved!');
    });


Deleting a file

The fs.unlink() method is used to remove a file or symbolic link from the file system.
This function does not work on directories, therefore it is recommended to use fs.rmdir() to remove a directory.

Syntax:
fs.unlink (path, callback)

Parameters: This method accepts two parameters as mentioned above and described below:
path: It is a string, Buffer or URL which represents the file or symbolic link which has to be removed.
callback: It is a function that would be called when the method is executed.
err: It is an error that would be thrown if the method fails.

Example:
    // Import the file system module
    const fs = require('fs');

    // Get the files in current directory before deletion
    getFilesInDirectory ();

    // Delete example_file.txt
    fs.unlink ("example_file.txt", (err) => {
    if (err) console.log (err);
    else {
    console.log("\nDeleted file: example_file.txt");

    // Get the files in current directory after deletion
    getFilesInDirectory();
    }
    }));

    // Function to get current filenames in directory with specific extension
    function getFilesInDirectory() {
    console.log("\nFiles present in directory:");
    let files = fs.readdirSync(__dirname);
    files.forEach(file => {
    console.log(file);
    });
    }


Truncate a file:

• The fs.ftruncate() method is used to change the size of the file i.e. either increase or decrease the file size.
• It changes the length of the file at the path by len bytes. If len is shorter than the file’s current length, the file is truncated to that length.
• If it is greater than the file length, it is padded (expanded)by appending null bytes (x00) until len is reached. It is similar to the truncate() method, except it accepts a file descriptor of the file to truncate.

Syntax:
fs.ftruncate(fd, len, callback)

Parameters
fd: It is an integer value which denotes the file descriptor of the file to truncate.
len: It is an integer value which specifies the length of the file after which the file will be truncated. It is an optional parameter. The default value is 0, which means that the whole file would be truncated.
callback: It is a function that would be called when the method is executed.
err: It is an error that would be thrown if the method fails.

Example:
    // Import the filesystem module
    const fs = require('fs');

    console.log("Contents of file before truncate:")
    console.log(fs.readFileSync('example_file.txt', 'utf8'));

    // Get the file descriptor of the file
    const fd = fs.open('example_file.txt', 'r+');

    fs.ftruncate(fd, 24, (err) => {
    if (err)
    console.log(err)
    else {
    console.log("Contents of file after truncate:")
    console.log(fs.readFileSync('example_file.txt', 'utf8'));
    }
    });


Append a file:


The fs.appendFile() method is used to asynchronously append the given data to a file. A new file is created if it does not exist.

Syntax:
fs.appendFile( path, data[, options], callback )

Parameters: This method accepts four parameters as mentioned above and described below:
path: It is a String, Buffer, URL or number that denotes the source filename or file descriptor that will be appended to.
data: It is a String or Buffer that denotes the data that has to be appended.
options: It is an string or an object that can be used to specify optional parameters that will affect the output. It has three optional parameters:
encoding: It is a string which specifies the encoding of the file. The default value is ‘utf8’.
mode: It is an integer which specifies the file mode. The default value is ‘0o666’.
flag: It is a string which specifies the flag used while appending to the file. The default value is ‘a’.
callback: It is a function that would be called when the method is executed.
err: It is an error that would be thrown if the method fails.

Example:
    // Import the filesystem module
    const fs = require('fs');

    // Get the file contents before the append operation
    console.log("\nFile Contents of file before append:",
    fs.readFileSync("example_file.txt", "utf8"));

    fs.appendFile("example_file.txt", "World", (err) => {
    if (err) {
    console.log(err);
    }
    else {
    // Get the file contents after the append operation
    console.log("\nFile Contents of file after append:",
    fs.readFileSync("example_file.txt", "utf8"));
    }
    });


Other Operation in file:


The fs.stat() method is used to return information about the given file or directory. It returns an fs.Stat object which has several properties and methods to get details about the file or directory.

Syntax:
fs.stat( path, options, callback )

Parameters: This method accept three parameters as mentioned above and described below:
path: It holds the path of the file or directory that has to be checked. It can be a String, Buffer or URL.
options: It is an object that can be used to specify optional parameters that will affect the output. It has one optional parameter:
bigint: It is a boolean value which specifies if the numeric values returned in the fs.Stats object are bigint. The default value is false.
callback: It is the function that would be called when the method is executed.
err: It is an error that would be thrown if the method
stats: It is the Stats object that contains the details of the file path.

Methods  Description
isFile(): returns true if the path is a file.
isDirectory(): returns true if the path is a directory.
isSymbolicLink(): returns true if the path is a symbolic link.
isFIFO() returns true if file type of a socket.
isBlockDevice() Return true if file type of a block device.


Property  Description
mode the file mode (permissions) represented as a number.
size the size of the file in bytes.
mtime the date and time the file was last modified.
ctime the date and time the file was last changed.
birthtime the date and time the file was created.
dev the device ID of the file system the file is located on.
uid the numeric user ID of the owner of the file.
gid the numeric group ID of the owner of the file.
blksize the block size of the file system.
blocks the number of blocks allocated to the file.


Program:

    const fs = require('fs');

    // specify the path of the file to check the stats for
    const filePath = 'example.txt';

    // use fs.stat() method to get the stats for the file
    fs.stat(filePath, (err, stats) => {
    if (err) {
    console.error(err);
    return;
    }

    // print out the various properties of the stats object
    console.log('File path: ${filePath}');
    console.log('File size: ${stats.size} bytes');
    console.log('Last modified: ${stats.mtime}');
    console.log('Is file: ${stats.isFile()}');
    console.log('Is directory: ${stats.isDirectory()}');
    });


2. Using read():

In Node.js, the read() method is used to read data from a file descriptor. It is a low-level method that is typically used with the fs module to read data from a file. The read() method takes four arguments:
1. fd: the file descriptor to read from
2. buffer: the buffer that the data will be written to
3. offset: the offset within the buffer where the data will be written
4. length: the number of bytes to read

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

Program:

    const fs = require('fs');

    // open a file for reading
    const fd = fs.openSync('example.txt', 'r');

    // create a buffer to hold the data
    const buffer = Buffer.alloc(10);

    // read data from the file into the buffer
    fs.read(fd, buffer, 0, 10, 0, (err, bytesRead, buffer) => {
    if (err) {
    console.error(err);
    return;
    }

    // print out the data that was read
    console.log(buffer.toString());

    // close the file descriptor
    fs.closeSync(fd);
    });


3. Using close():

In Node.js, the close() method is used to close a file descriptor.

Syntax:
fs.close(fd,callback);

1. fd: the file descriptor to close.
2. callback: a function to call when the file has been closed.

Program:

    const fs = require('fs');

    // open a file for reading
    const fd = fs.openSync('example.txt', 'r');

    // read some data from the file

    // close the file descriptor
    fs.close(fd, (err) => {
    if (err) {
    console.error(err);
    return;
    }

    console.log('File closed');
    });


Handling Exceptions & errors

Using promises: You can also use promises to handle errors when working with files.

Program:

    const fs = require('fs').promises;

    fs.readFile('example.txt', 'utf8')

    .then((data) => {
    console.log(data);
    })
    .catch((err) => {
    console.error(err);
    })

No comments:

Post a Comment