File System Module (fs module)
1. fs.access(path,mode,callback):
Checks the user's permissions for the specified file or directory.
path(string): The file or directory path.
mode(integer): optional Determines the accessibility checks to be performed.
callback:(function): Callback function to be called with any error.
Examples:
// Example 1: Checking if a file exists and is readable fs.access('/path/to/file.txt', fs.constants.F_OK | fs.constants.R_OK, (err) => { if (err) { console.error("File does not exist or is not readable"); } else { console.log("File exists and is readable"); } }); // Example 2: Checking if a directory is writable fs.access('/path/to/directory', fs.constants.W_OK, (err) => { if (err) { console.error("Directory is not writable"); } else { console.log("Directory is writable"); } }); // Example 3: Checking if a file can be executed fs.access('/path/to/script.sh', fs.constants.X_OK, (err) => { if (err) { console.error("Script is not executable"); } else { console.log("Script is executable"); } });
- fs.mkdir(path, options, callback):
Creates a new directory with the specified path.
path
(string): The directory path.options
(object): Optional - Options for directory creation.callback
(function): Callback function to be called with any error.// Example 1: Creating a new directory fs.mkdir('/path/to/new-directory', (err) => { if (err) { console.error("Error creating directory:", err); } else { console.log("Directory created successfully"); } }); // Example 2: Creating a nested directory with recursive option fs.mkdir('/path/to/new/nested/directory', { recursive: true }, (err) => { if (err) { console.error("Error creating directory:", err); } else { console.log("Directory created successfully"); } }); // Example 3: Creating a directory with specific permissions fs.mkdir('/path/to/new-directory', { mode: 0o755 }, (err) => { if (err) { console.error("Error creating directory:", err); } else { console.log("Directory created successfully"); } });
3.fs.readdir(path, options, callback):
Reads the contents of a directory.
path
(string): The directory path.options
(object): Optional - Options for directory reading.callback
(function): Callback function to be called with any error and the array of filenames.
Examples:
// Example 1: Reading contents of a directory
fs.readdir('/path/to/directory', (err, files) => {
if (err) {
console.error("Error reading directory:", err);
} else {
console.log("Files in directory:", files);
}
});
// Example 2: Reading contents of a directory with specified encoding
fs.readdir('/path/to/directory', { encoding: 'utf8' }, (err, files) => {
if (err) {
console.error("Error reading directory:", err);
} else {
console.log("Files in directory:", files);
}
});
// Example 3: Reading contents of a directory and filtering by file extension
fs.readdir('/path/to/directory', (err, files) => {
if (err) {
console.error("Error reading directory:", err);
} else {
const txtFiles = files.filter(file => file.endsWith('.txt'));
console.log("Text files in directory:", txtFiles);
}
});
4.fs.readFile(path, options, callback):
Reads the contents of a file.
path
(string): The file path.options
(object): Optional - Options for file reading.callback
(function): Callback function to be called with any error and the file data.
Examples:
// Example 1: Reading contents of a file
fs.readFile('/path/to/file.txt', 'utf8', (err, data) => {
if (err) {
console.error("Error reading file:", err);
} else {
console.log("File contents:", data);
}
});
// Example 2: Reading contents of a binary file
fs.readFile('/path/to/image.png', (err, data) => {
if (err) {
console.error("Error reading file:", err);
} else {
console.log("File size:", data.length);
}
});
// Example 3: Reading contents of a file and processing asynchronously
fs.readFile('/path/to/file.txt', 'utf8', (err, data) => {
if (err) {
console.error("Error reading file:", err);
} else {
setTimeout(() => {
console.log("File contents:", data);
}, 1000);
}
});
fs.writeFile(file, data, options, callback):
Writes data to a file, replacing the file if it already exists.
file
(string): The file path.data
(string | Buffer): The data to write.options
(object): Optional - Options for file writing.callback
(function): Callback function to be called with any error.
Examples:
// Example 1: Writing data to a file
fs.writeFile('/path/to/file.txt', 'Hello, world!', (err) => {
if (err) {
console.error("Error writing to file:", err);
} else {
console.log("Data written to file");
}
});
// Example 2: Writing data to a file asynchronously
const data = 'Lorem ipsum dolor sit amet';
fs.writeFile('/path/to/file.txt', data, (err) => {
if (err) {
console.error("Error writing to file:", err);
} else {
console.log("Data written to file");
}
});
// Example 3: Writing data to a file with specified encoding
const buffer = Buffer.from('Hello, world!', 'utf8');
fs.writeFile('/path/to/file.txt', buffer, { encoding: 'utf8' }, (err) => {
if (err) {
console.error("Error writing to file:", err);
} else {
console.log("Data written to file");
}
});
6.fs.rename(oldPath, newPath, callback):
Renames a file or directory.
oldPath
(string): The current file or directory path.newPath
(string): The new file or directory path.callback
(function): Callback function to be called with any error.
Examples:
// Example 1: Renaming a file
fs.rename('/path/to/old-file.txt', '/path/to/new-file.txt', (err) => {
if (err) {
console.error("Error renaming file:", err);
} else {
console.log("File renamed successfully");
}
});
// Example 2: Renaming a directory
fs.rename('/path/to/old-directory', '/path/to/new-directory', (err) => {
if (err) {
console.error("Error renaming directory:", err);
} else {
console.log("Directory renamed successfully");
}
});
// Example 3: Moving a file to a different directory
fs.rename('/path/to/old-file.txt', '/new-path/new-file.txt', (err) => {
if (err) {
console.error("Error moving file:", err);
} else {
console.log("File moved successfully");
}
});
7.fs.unlink(path, callback):
Deletes a file or symbolic link.
path
(string): The file path.callback
(function): Callback function to be called with any error.
Examples:
// Example 1: Deleting a file
fs.unlink('/path/to/file.txt', (err) => {
if (err) {
console.error("Error deleting file:", err);
} else {
console.log("File deleted successfully");
}
});
// Example 2: Deleting a symbolic link
fs.unlink('/path/to/symlink', (err) => {
if (err) {
console.error("Error deleting symlink:", err);
} else {
console.log("Symlink deleted successfully");
}
});
// Example 3: Handling file deletion asynchronously
fs.unlink('/path/to/file.txt', (err) => {
if (err) {
console.error("Error deleting file:", err);
} else {
setTimeout(() => {
console.log("File deleted successfully");
}, 1000);
}
});
fs.rmdir(path, callback):
Removes an empty directory.
path
(string): The directory path.callback
(function): Callback function to be called with any error.
Examples:
// Example 1: Removing an empty directory
fs.rmdir('/path/to/empty-directory', (err) => {
if (err) {
console.error("Error removing directory:", err);
} else {
console.log("Directory removed successfully");
}
});
// Example 2: Handling directory removal asynchronously
fs.rmdir('/path/to/empty-directory', (err) => {
if (err) {
console.error("Error removing directory:", err);
} else {
setTimeout(() => {
console.log("Directory removed successfully");
}, 1000);
}
});
// Example 3: Error handling when directory is not empty
fs.rmdir('/path/to/non-empty-directory', (err) => {
if (err) {
console.error("Error removing directory:", err);
} else {
console.log("Directory removed successfully");
}
});
fs.stat(path, callback):
Provides information about a file.
path
(string): The file path.callback
(function): Callback function to be called with any error and the file stats object.
Examples:
// Example 1: Getting file information
fs.stat('/path/to/file.txt', (err, stats) => {
if (err) {
console.error("Error getting file stats:", err);
} else {
console.log("File stats:", stats);
}
});
// Example 2: Checking if a path is a file
fs.stat('/path/to/file.txt', (err, stats) => {
if (err) {
console.error("Error getting file stats:", err);
} else {
console.log("Is file?", stats.isFile());
}
});
// Example 3: Checking if a path is a directory
fs.stat('/path/to/directory', (err, stats) => {
if (err) {
console.error("Error getting file stats:", err);
} else {
console.log("Is directory?", stats.isDirectory());
}
});
fs.watch(filename, options, listener):
Watches for changes on a file or directory.
filename
(string): The file or directory to watch.options
(object): Optional - Options for watching.listener
(function): Callback function to be called when changes occur.
Examples:
// Example 1: Watching for changes on a file fs.watch('/path/to/file.txt', (event, filename) => { console.log(`File ${filename} ${event}`); }); // Example 2: Watching for changes on a directory fs.watch('/path/to/directory', (event, filename) => { console.log(`File ${filename} ${event}`); }); // Example 3: Watching for changes with specific options fs.watch('/path/to/directory', { recursive: true }, (event, filename) => { console.log(`File ${filename} ${event}`); });
11. fs.createReadStream(path, options):
Creates a readable stream to read data from a file.
path
(string): The file path.options
(object): Optional - Options for stream creation.
Examples:
// Example 1: Creating a readable stream to read data from a file
const readable = fs.createReadStream('/path/to/file.txt');
readable.on('data', (chunk) => {
console.log(`Received ${chunk.length} bytes of data`);
});
// Example 2: Reading file data asynchronously using a readable stream
const readable = fs.createReadStream('/path/to/file.txt', { encoding: 'utf8' });
readable.on('data', (chunk) => {
console.log("Chunk of data:", chunk);
});
readable.on('end', () => {
console.log("End of file reached");
});
// Example 3: Error handling with a readable stream
const readable = fs.createReadStream('/path/to/non-existent-file.txt');
readable.on('error', (err) => {
console.error("Error reading file:", err);
});
fs.createWriteStream(path, options):
Creates a writable stream to write data to a file.
path
(string): The file path.options
(object): Optional - Options for stream creation.
Examples:
// Example 1: Creating a writable stream to write data to a file
const writable = fs.createWriteStream('/path/to/output.txt');
writable.write('Hello, world!');
writable.end();
// Example 2: Writing data to a file asynchronously using a writable stream
const writable = fs.createWriteStream('/path/to/output.txt', { encoding: 'utf8' });
writable.write('Lorem ipsum dolor sit amet');
writable.end();
// Example 3: Error handling with a writable stream
const writable = fs.createWriteStream('/path/to/readonly-file.txt');
writable.on('error', (err) => {
console.error("Error writing to file:", err);
});
writable.write('Hello, world!');
writable.end();