The fs module provides an API for interacting with the file system. It supports both synchronous and asynchronous operations.
Sync vs Async
Synchronous methods block the event loop until complete. Use them only during startup or in scripts. Always prefer async methods in servers.
Reading Files
Use fs.readFile for small files, fs.createReadStream for large files. Choose the right encoding (utf8 for text, null for binary).
Writing Files
Use fs.writeFile for complete overwrites, fs.appendFile for adding to files. For large data, use streams.
Working with Directories
Create directories with fs.mkdir, list contents with fs.readdir, and recursively work with directories using the recursive option.
File Watching
Monitor files and directories for changes using fs.watch or fs.watchFile. Useful for development tools and live reload.