What is fs?
The 'fs' package in Node.js provides an API for interacting with the file system in a manner closely modeled around standard POSIX functions. It allows you to perform operations such as reading, writing, updating, and deleting files and directories.
What are fs's main functionalities?
Reading Files
This feature allows you to read the contents of a file asynchronously. The 'readFile' method takes the file path, encoding, and a callback function to handle the file data or error.
const fs = require('fs');
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
Writing Files
This feature allows you to write data to a file asynchronously. The 'writeFile' method takes the file path, data to write, and a callback function to handle any errors.
const fs = require('fs');
fs.writeFile('example.txt', 'Hello, world!', (err) => {
if (err) throw err;
console.log('File has been saved!');
});
Updating Files
This feature allows you to append data to an existing file. The 'appendFile' method is used to add data to the end of a file asynchronously.
const fs = require('fs');
fs.appendFile('example.txt', ' More data.', (err) => {
if (err) throw err;
console.log('Data has been appended!');
});
Deleting Files
This feature allows you to delete a file. The 'unlink' method is used to remove a file asynchronously.
const fs = require('fs');
fs.unlink('example.txt', (err) => {
if (err) throw err;
console.log('File has been deleted!');
});
Creating Directories
This feature allows you to create a new directory. The 'mkdir' method can create a directory and, with the 'recursive' option, can create nested directories.
const fs = require('fs');
fs.mkdir('newDir', { recursive: true }, (err) => {
if (err) throw err;
console.log('Directory created!');
});
Other packages similar to fs
fs-extra
The 'fs-extra' package builds on the standard 'fs' module by adding more methods and making some of the existing methods more convenient to use. It provides additional functionality like copying, moving, and ensuring file and directory existence, which are not available in the standard 'fs' module.
graceful-fs
The 'graceful-fs' package is a drop-in replacement for the 'fs' module that improves the handling of EMFILE errors (too many open files) by queueing the operations. It is useful in environments where you might hit the file descriptor limit.
node-fs
The 'node-fs' package is an extension of the 'fs' module that provides additional methods for file and directory operations, such as recursive directory creation and file copying. It offers more features than the standard 'fs' module but is less commonly used than 'fs-extra'.
Security holding package
This package name is not currently in use, but was formerly occupied
by another package. To avoid malicious use, npm is hanging on to the
package name, but loosely, and we'll probably give it to you if you
want it.
You may adopt this package by contacting support@npmjs.com and
requesting the name.