The 'fs' module in Node.js is primarily used for interacting with the file system. It provides a set of methods that enable developers to perform file operations within the Node.js environment, such as reading, writing, and deleting files. This is a crucial module for handling files in server-side JavaScript applications.
fs module's main functionalities include:
-
File read/write
- Synchronous read/write:
fs.readFileSync(),fs.writeFileSync(), etc. - Asynchronous read/write:
fs.readFile(),fs.writeFile(), etc., which handle asynchronous operations via callback functions.
- Synchronous read/write:
-
File management
- Creating directories:
fs.mkdir() - Reading directory contents:
fs.readdir() - Deleting files or directories:
fs.unlink(),fs.rmdir()
- Creating directories:
-
File monitoring
- You can monitor changes to files or directories using the
fs.watch()orfs.watchFile()methods.
- You can monitor changes to files or directories using the
Application example
Suppose we need to develop an application that reads a CSV file uploaded by a user, parses its contents, and stores it in a database. In this process, we can use the fs module to implement file reading and parsing:
javascriptconst fs = require('fs'); // Asynchronous file reading fs.readFile('/path/to/file.csv', 'utf8', (err, data) => { if (err) { console.error('File read error:', err); return; } console.log('File content:', data); // Add logic to parse CSV and store in database here });
In this example, we use the fs.readFile() method to asynchronously read the file content and process the read data within the callback function. This asynchronous approach effectively avoids blocking the Node.js event loop, allowing the application to handle more concurrent requests.