The fs (File System) module in Node.js is a powerful tool for working with the file system, allowing you to interact with files and directories on your server. It's built into Node.js, so you don't need to install anything extra to use it. Let's explore how fs works and its key functions.
The fs module provides an API for interacting with the file system in a manner closely modeled around standard POSIX functions. This module is used for tasks like reading from and writing to files, creating directories, and more.
To use the fs module, you need to require it at the beginning of your Node.js script:
const fs = require('fs');
There are two primary ways to read files: asynchronously and synchronously.
This method is non-blocking, meaning it won't stop the execution of your program while it reads the file.
fs.readFile('example.txt', 'utf8', (err, data) => { if (err) { console.error(err); return; } console.log(data); });
This method is blocking, meaning it will stop the execution of your program until the file is read.
try { const data = fs.readFileSync('example.txt', 'utf8'); console.log(data); } catch (err) { console.error(err); }
Similar to reading files, writing can also be done asynchronously or synchronously.
fs.writeFile('example.txt', 'Hello, World!', (err) => { if (err) { console.error(err); return; } console.log('File has been saved!'); });
try { fs.writeFileSync('example.txt', 'Hello, World!'); console.log('File has been saved!'); } catch (err) { console.error(err); }
If you want to add content to an existing file without overwriting it, use the appendFile method.
fs.appendFile('example.txt', '\nAppended Content', (err) => { if (err) { console.error(err); return; } console.log('Content has been appended!'); });
try { fs.appendFileSync('example.txt', '\nAppended Content'); console.log('Content has been appended!'); } catch (err) { console.error(err); }
To delete a file, use the unlink method.
fs.unlink('example.txt', (err) => { if (err) { console.error(err); return; } console.log('File deleted!'); });
try { fs.unlinkSync('example.txt'); console.log('File deleted!'); } catch (err) { console.error(err); }
fs.mkdir('newDir', { recursive: true }, (err) => { if (err) { console.error(err); return; } console.log('Directory created!'); });
fs.readdir('newDir', (err, files) => { if (err) { console.error(err); return; } console.log('Files in directory:', files); });
fs.rmdir('newDir', { recursive: true }, (err) => { if (err) { console.error(err); return; } console.log('Directory deleted!'); });
You can watch for changes in a file using the fs.watch method:
fs.watch('example.txt', (eventType, filename) => { if (filename) { console.log(`${filename} file Changed!`); } });
Node.js provides fs streams for handling large files that may not fit into memory.
const readStream = fs.createReadStream('example.txt', 'utf8'); readStream.on('data', (chunk) => { console.log(chunk); });
const writeStream = fs.createWriteStream('example.txt'); writeStream.write('Hello, '); writeStream.write('World!'); writeStream.end();
Node.js provides a simple method for copying files:
fs.copyFile('source.txt', 'destination.txt', (err) => { if (err) { console.error(err); return; } console.log('File copied successfully!'); });
The fs module also has promise-based methods, making it easier to work with modern JavaScript features like async/await.
const fsPromises = require('fs').promises; async function readFile() { try { const data = await fsPromises.readFile('example.txt', 'utf8'); console.log(data); } catch (err) { console.error(err); } } readFile();
The fs module is versatile and essential for any Node.js application that needs to interact with the file system. By understanding its various methods, handling streams efficiently, and employing best practices, you'll be well-equipped to manage file operations in Node.js effectively and securely.
Remember to consult the official Node.js documentation for the most up-to-date information and additional features of the fs module.
The above is the detailed content of File System: Node.js `fs` Module. For more information, please follow other related articles on the PHP Chinese website!