The fs
module in Node.js is a built-in module that provides functionality for interacting with the file system. It allows you to perform various operations related to files and directories, such as reading and writing files, creating directories, deleting files, and more. The module provides both synchronous and asynchronous methods for these operations.
Here’s an overview of some commonly used functions provided by the fs
module:
Reading Files:
fs.readFile(path, [options], callback)
: Asynchronously reads the contents of a file. The contents can be returned as a buffer or a string, depending on the encoding specified.
Writing Files:
fs.writeFile(file, data, [options], callback)
: Asynchronously writes data to a file. If the file does not exist, it will be created. If it does exist, its contents will be overwritten.
Asynchronous Version Example:
const fs = require('fs');
fs.writeFile('file.txt', 'Hello, world!', 'utf8', (err) => {
if (err) {
console.error('Error writing file:', err);
return;
}
console.log('File written successfully.');
});
Synchronous Version Example:
const fs = require('fs');
try {
fs.writeFileSync('file.txt', 'Hello, world!', 'utf8');
console.log('File written successfully.');
} catch (err) {
console.error('Error writing file:', err);
}
Reading and Writing Streams:
fs.createReadStream(path, [options])
: Creates a readable stream for reading from a file.fs.createWriteStream(path, [options])
: Creates a writable stream for writing to a file.
Creating Directories:
fs.mkdir(path, [options], callback)
: Asynchronously creates a directory.
Deleting Files or Directories:
fs.unlink(path, callback)
: Asynchronously deletes a file.fs.rmdir(path, callback)
: Asynchronously deletes an empty directory.
Checking File or Directory Existence:
fs.existsSync(path)
: Synchronously checks if a file or directory exists.
These are just a few examples of the functions provided by the fs
module. Remember that when using asynchronous methods, you provide a callback function that will be executed once the operation is complete. Using synchronous methods blocks the execution until the operation is finished, so they are often best avoided in scenarios where you want to keep your application responsive.
The fs
module is a powerful tool for handling file-related tasks in Node.js applications and is widely used for file I/O, data persistence, and various other scenarios where interaction with the file system is required.