How to Work with Files and Folders in Node.js

How to Work with Files in Node.js

Node.js, as a server-side JavaScript runtime, provides a rich set of core modules to interact with the file system. The “fs” module, short for the file system, offers a range of functions for performing file-related operations so you can work with files. In this tutorial, you will learn the key functionalities of the fs module for working with files and directories in Node.js. Such as how to read and write files, as well as perform various file operations.

The Node.js “fs” File-System Module

The Node.js “fs” (File System) module is a built-in module that provides functions for interacting with the file system. It allows you to perform various file-related operations such as reading from and writing to files, creating and deleting files and directories, modifying file permissions, and more.

The “fs” module is part of the Node.js core, which means it comes pre-installed with Node.js, so you don’t need to install it separately. You can simply require it in your Node.js application to start using its functionality.

const fs = require('fs');

Now, let’s dive into the major features and functions the fs module offers:

Reading Files in Node.js:

The fs.readFile() method asynchronously reads the contents of a file. It takes the file path, an optional encoding parameter, and a callback.

const fs = require('fs');

fs.readFile('example.txt', 'utf8', (err, data) => {
    if (err) {
        console.error('Error reading file:', err);
        return;
    }
    console.log('File contents:', data);
});

In Node.js, developers use the fs.readFileSync() function to synchronously read the contents of a file. It takes in two arguments:

const fs = require("fs");

// Reading a file synchronously
try {
    const data = fs.readFileSync("example.txt", "utf8");
    console.log("File content:", data);
} catch (err) {
    console.error("Error reading file:", err);
}

Writing Files in Node.js:

The fs.writeFile() method is used to asynchronously write data to a file. It takes the file path, data to be written, an optional encoding parameter, and a callback function.

const fs = require('fs');
const content = 'Hello, Node.js!';
fs.writeFile('output.txt', content, 'utf8', (err) => {
    if (err) {
        console.error('Error writing to file:', err);
        return;
    }
    console.log('File written successfully!');
});

However there is a method called fs.writeFileSync() for writing file synchronously. Here is an example:

const fs = require("fs");

// Data to be written to the file
const data = "Hello, world!";

// File path
const filePath = "example.txt";

// Writing data to the file synchronously
try {
    fs.writeFileSync(filePath, data, "utf8");
    console.log("File written successfully!");
} catch (err) {
    console.error("Error writing file:", err);
}

Create Directory or Folder using Node.js:

The fs.mkdir() method is used to asynchronously create a directory. It takes the directory path, optional options object, and a callback. Here is an example:

const fs = require('fs');
fs.mkdir('/path/to/new-directory-name', { recursive: true }, (err) => {
    if (err) {
        console.error('Error creating directory:', err);
        return;
    }
    console.log('Directory created successfully!');
});

In Node.js, when the “recursive” option is set to true in functions like fs.mkdir() or fs.rmdir(), it indicates that the operation should create or remove directories recursively, including any parent directories that do not exist.

For example, consider the following directory structure:

parentDir
└── childDir
    └── grandchildDir

If you want to create the grandchildDir directory and the parentDir and childDir directories do not exist, setting recursive to true will create all necessary parent directories:

const fs = require("fs");

const dirPath = "parentDir/childDir/grandchildDir";

fs.mkdir(dirPath, { recursive: true }, (err) => {
    if (err) {
        console.error("Error creating directory:", err);
        return;
    }
    console.log("Directory created successfully!");
});

In this example, even though parentDir and childDir do not exist, they will be created automatically along with grandchildDir due to the recursive option being set to true. This behavior simplifies directory creation or removal when dealing with complex directory structures.

Reading Contents of a Directory:

The fs.readdir() method is used to asynchronously read the contents of a directory. It takes the directory path and a callback function.

const fs = require('fs');
fs.readdir('/path/to/directory', (err, files) => {
    if (err) {
        console.error('Error reading directory:', err);
        return;
    }
    console.log('Directory contents:', files);
});

Get File and Directory Information in Node.js

The fs.stat() method is used to asynchronously retrieve information about a file or directory. It takes the file or directory path and a callback function.

const fs = require('fs');
fs.stat('example.txt', (err, stats) => {
    if (err) {
        console.error('Error retrieving file information:', err);
        return;
    }
    console.log('File information:', stats);
});

Rename Files and Folders in Node.js

The fs.rename() method is used to asynchronously rename a file or directory. It takes the current path, the new path, and a callback function.

If you want to rename a folder, then provide the old-folder-name and new-folder-name to the fs.rename().

const fs = require('fs');
fs.rename('old-file.txt', 'new-file.txt', (err) => {
    if (err) {
        console.error('Error renaming file:', err);
        return;
    }
    console.log('File renamed successfully!');
});

Delete Files and Directories in Node.js

The fs.unlink() method is used to asynchronously delete a file. It takes the file path and a callback function.

const fs = require('fs');
fs.unlink('file-to-delete.txt', (err) => {
    if (err) {
        console.error('Error deleting file:', err);
        return;
    }
    console.log('File deleted successfully!');
});

To delete folders in node.js you can use the fs.rmdir() function which for deleting directories asynchronously. Here’s how you can use it:

const fs = require("fs");

// Directory path to remove
const dirPath = "myDirectory";

// Removing the directory asynchronously
fs.rmdir(dirPath, (err) => {
    if (err) {
        console.error("Error removing directory:", err);
        return;
    }
    console.log("Directory removed successfully!");
});

Versions of “fs” Functions:

The fs (File System) module in Node.js offers both synchronous and asynchronous versions of many of its functions for file and directory manipulation.

  • Synchronous Versions: Functions with names ending in Sync are synchronous and block the execution of your code until the operation is completed. For example, fs.readFileSync() reads a file synchronously.
  • Asynchronous Versions: Functions without the Sync suffix are asynchronous and do not block the execution of your code. Instead, they use callbacks or Promises to handle the result of the operation once it’s completed. For example, fs.readFile() reads a file asynchronously.

It’s generally recommended to use the asynchronous versions in most cases, especially in applications that require high concurrency and responsiveness. Synchronous functions can block the event loop, leading to decreased performance and scalability, particularly in server-side applications. However, synchronous functions may be suitable for certain scenarios, such as command-line scripts or situations where simplicity is more important than performance.

Leave a Reply

Your email address will not be published. Required fields are marked *

We use cookies to ensure that we give you the best experience on our website. Privacy Policy