File System & Path in Node.js

Level : Beginner
Mentor: Shailendra Chauhan
Duration : 00:08:00

What is a Path?

Path modules are used to normalize, join, and resolve paths. It helps in finding related pathways, extracting components from paths, and determining the presence of paths. The path module just manipulates strings and does not interface with the file system to validate paths.

Path Methods and Properties 

  • basename(): This function returns the filename or directory name from a provided path string. It ignores the directory path and returns only the final portion of it, which is usually the file or directory name.
  • delimiter: The delimiter property describes the character(s) used to divide individual path segments in the system. For example, in Unix-like systems, the delimiter is often ":", whereas in Windows, it is commonly ";".
  • dirname(): When working with file paths, the dirname() method is useful for isolating and retrieving the directory component of the path. It returns everything in the path except the last section, which is typically the file or directory name.
  • extname(): Use this function to determine the file extension of a specified path. It correctly detects the extension, including the dot (".") character, at the end of the file path.
  • format(): This function helps you convert a path object into a string representation of the path. It's very beneficial when you have to serialize path objects for storage or transmission.
  • isAbsolute(): The isAbsolute() function determines if a path is absolute or relative. It returns true if the path is absolute (starts at the root directory), and false otherwise.
  • join(): When you need to concatenate multiple path segments into a single path, use the join() method. It successfully merges the segments and resolves any relative path components.
  • normalize (): Path normalization is necessary for maintaining consistency and deleting unnecessary elements such as "." and ".." The normalize() method does this by resolving and standardizing the route.
  • parse(): The parse() function is used to determine the various components of a path string, such as root, directory, base, extension, and file name. It returns an object that includes these components for simpler manipulation.
  • posix: This module gives you access to POSIX-specific properties and methods, allowing you to handle paths and associated actions differently depending on the platform.
  • relative(): The relative() function is useful for calculating the relative path between two supplied pathways. It calculates the relative path from a beginning path to a target path, making it easier to navigate directory hierarchies.
  • resolve(): The resolve() method makes it easier to create absolute paths by combining and resolving several path segments beginning with the root directory. It provides constant and dependable absolute path creation.
  • sep: The sep attribute describes the segment separator used in pathways on the present platform. For example, in Unix-like systems, it is "/", whereas, in Windows, it is "".
  • win32: Like posix, this module gives access to properties and methods native to Windows operating systems, allowing for platform-specific path handling and operations.

File System

The file system provides file and directory I/O functionality. All file system functions have two versions: synchronous (blocking) and asynchronous (non-blocking). Synchronous functions with "Sync" in their name return the value immediately and prevent Node from running any code while I/O is completed. Asynchronous functions use the value as a parameter for a callback function.​

Common use for the File System module

The File System (fs) module in Node.js provides several typical purposes:

  • Read Files: It is possible to read the contents of files using functions such as fs.readFile() or fs.createReadStream(), giving you access to file data for processing or display.
  • Write Files: The module makes it easier to write data to files by providing functions such as fs.writeFile() and fs.createWriteStream(), which allow you to create or overwrite files with specific content.
  • Append Files: The fs module, with calls like fs.appendFile(), allows you to append data to existing files without overwriting their contents. This is handy for adding new information to files without interrupting existing data.
  • Close Files: After you've opened a file for reading or writing, you should close it to free up resources. Functions like fs.close() help with appropriately closing file descriptors after activities are performed.
  • Delete Files: The fs module has functions for deleting files from the file system, such as fs.unlink(), which allow you to remove unwanted or obsolete files.

File System Functions

  • fs.open(path, flags, [mode], callback): Opens the file specified by path using the provided flags to indicate the mode of file access. You can optionally define the file mode. Upon completion, the callback is passed any exceptions as the first argument and a file descriptor as the second.
  • fs.close(fd, callback): Closes the file descriptor fd, which was earlier opened with fs.open. Upon completion, the callback receives any exceptions that occurred during the procedure.
  • fs.rename(oldName, newName, callback): Renames an existing file to a new name. Any exceptions thrown during the operation are routed to the callback function.
  • fs.unlink(path, callback): Deletes the file identified by path. Any exceptions thrown during the operation are routed to the callback function.​
  • fs.truncate(path, len, callback): Reduces the file at path to the supplied len bytes. If len exceeds the current file size, the file is padded with null bytes. Any exceptions thrown during the operation are routed to the callback function.
  • fs.chown(path, uid, gid, callback): Transfers ownership of the file at the path to the supplied user ID and group ID. Any exceptions thrown during the operation are routed to the callback function.
  • fs.chmod(path, mode, callback): Sets the mode (permissions) of the file at path to the desired mode. Any exceptions thrown during the operation are routed to the callback function.
  • fs.stat(path, callback): Returns the properties of the file at path, including size, timestamps, and permissions. Any exceptions thrown during the operation are routed to the callback function.
  • fs.read(fd, buffer, offset, length, position, callback): Reads data from the file referenced by the file descriptor fd into the buffer, beginning at the specified offset and reading the specified length of bytes. The position option determines where to start reading from within the file. Any exceptions thrown during the operation are routed to the callback function.
  • fs.readFile(path, [options], callback): reads the whole contents of the file at path. The options parameter is optional and can include parameters such as encoding. The callback receives any exceptions that occur during the process, as well as the file contents.
  • fs.writeFile(path, data, callback): Writes the provided data to the path-specified file, replacing any existing files. Any exceptions thrown during the operation are routed to the callback function.
  • fs.appendFile(path, data, [options], callback): Appends the specified data to the end of the file at the path. The options parameter is optional and can include parameters such as encoding. Any exceptions thrown during the operation are routed to the callback function.
  • fs.createWriteStream(path, [options]): Returns a writable stream that can be used to write data to the supplied file path. The options parameter is optional and can include parameters such as encoding.
  • fs.createReadStream(path, [options]): Returns a readable stream that may read data from the file specified by path. The options parameter is optional and can include parameters such as encoding.
  • fs.readdir(path, callback): Returns the contents of the directory supplied by the path. The callback receives any exceptions thrown during the process, as well as an array of directory items.
  • fs.mkdir(path[, mode], callback): Generates a new directory using the provided path. You can optionally define the directory permission mode. Any exceptions thrown during the operation are routed to the callback function.
  • fs.rmdir(path, [callback]): Removes the directory identified by path. If the directory is not empty, it will fail unless a callback is specified. Any exceptions thrown during the operation are routed to the callback function.

File Descriptors

A file descriptor is a numeric identifier allocated to an open file. Programs can read and write data to the file. The fs module in Node.js uses file descriptors to abstract over Unix-like and Windows file handles. 

Asynchronous File Appending with the fs Module

The fs.appendFile function in Node.js, which is part of the File System (fs) module, is specifically built to asynchronously append data to a file. Its asynchronous nature prevents it from blocking the Node.js event loop, enabling efficient handling of concurrent tasks.

Changing File Ownership using the fs Module

The fs. chown method is part of the Node.js File System (fs) module. It changes the owner and group of a file or directory. fs.chown modifies the user ID (UID) and group ID (GID) of a file system object based on its path. 

Truncating Files with the fs Module

fs.truncate(path, len, callback) reduces the file at the specified path by len bytes. It can either reduce or extend the size of an existing file, depending on its present length. If len is higher, the file length is padded with null bytes (\x00) until it is reached.

Self-paced Membership
  • 24+ Video Courses
  • 825+ Hands-On Labs
  • 400+ Quick Notes
  • 125+ Skill Tests
  • 10+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support
Upto 60% OFF
Know More
Still have some questions? Let's discuss.
CONTACT US
Accept cookies & close this