Node.js File system

Node.js File system

Introduction

Understanding the file system in Node.js is essential for developing applications that require reading, writing, and manipulating files. Node.js offers the fs module, which enables synchronous and asynchronous file management. This article explains in detail how to use the fs module in Node.js.

fs module is part of the Node.js API that allows working with the file system. The module can be loaded using the require function:

file system

Reading files

To read the contents of the file, you can use fs.readFile for asynchronous reading or fs.readFileSync for synchronous reading. For example:

Asynchronous reading with callback:

Asynchronous reading with promises:

Synchronous reading:

Writing to files

For writing to files, the fs module offers fs.writeFile for asynchronous writing and fs.writeFileSync for synchronous writing. For example:

Asynchronous write with callback:

Asynchronous writing with promises:

Synchronous writing:

Writing open file

If we want to have detailed control over the writing process, including the ability to determine how the writing will take place (creating a new file, appending to the end of an existing one, etc.) and the ability to manage resources then we can apply the following approach:

Working with directories

fs module also allows creating, reading and deleting directories. For example:

Creating directory with callback:

Creating directory with promises:

Reading directory contents with callback:

Read directory with promises:

Delete directory with callback:

Reading open file

If we still want to have fine control over reading, such as specifying the exact position where you want to start reading within the file and how much data you want to read then we can use the following approach

It would be desirable to adjust the buffer to the size of the file, and we will do this using fs.fstat (or fs.stat for asynchronously obtaining information about the file before reading), where we will allocate the buffer exactly according to the file content, which makes reading more efficient, especially for smaller files.

Delete directory with promises:

Tracking file changes

In Node.js, the watch method from the fs module allows monitoring changes to files or directories. This functionality is useful when you want to automatically respond to changes, such as file updates, without having to manually refresh or restart the application. Here’s how it works:

Or with the use of promis:

When you use fs.watch, it can emit two main types of events: ‘change’ and ‘rename’. The ‘change’ event refers to a change in the contents of a file, while ‘rename’ indicates a change in the directory structure (eg creating a new file, renaming or deleting a file).