File System (fs)
Thenode:fs module enables interacting with the file system in a way modeled on standard POSIX functions.
Import
API Forms
All file system operations have three forms:- Promises API - Returns promises (recommended for async operations)
- Callback API - Takes completion callbacks as last argument
- Synchronous API - Blocks the event loop until operation completes
Promise Example
Callback Example
Synchronous Example
File Descriptors
On POSIX systems, for every process, the kernel maintains a table of currently open files and resources. Each open file is assigned a simple numeric identifier called a file descriptor.Working with File Descriptors
Core Methods
Reading Files
fs.readFile(path[, options])
Asynchronously reads the entire contents of a file.
Parameters:
path- Filename or file descriptoroptions- Encoding, flag, or signal options
fs.readFileSync(path[, options])
Synchronous version of readFile().
fs.read(fd, buffer, offset, length, position)
Reads data from a file descriptor into a buffer.
Writing Files
fs.writeFile(file, data[, options])
Asynchronously writes data to a file, replacing it if it already exists.
fs.appendFile(path, data[, options])
Appends data to a file, creating the file if it doesn’t exist.
fs.write(fd, buffer, offset, length, position)
Writes buffer to the file descriptor.
File Operations
fs.open(path, flags[, mode])
Opens a file and returns a file handle.
Flags:
'r'- Open for reading (default)'w'- Open for writing (truncates file)'a'- Open for appending'r+'- Open for reading and writing'w+'- Open for reading and writing (truncates)'a+'- Open for reading and appending
fs.close(fd)
Closes a file descriptor.
fs.rename(oldPath, newPath)
Renames a file or directory.
fs.unlink(path)
Removes a file or symbolic link.
fs.copyFile(src, dest[, mode])
Copies a file from source to destination.
Directory Operations
fs.mkdir(path[, options])
Creates a directory.
fs.readdir(path[, options])
Reads the contents of a directory.
fs.rmdir(path[, options])
Removes a directory.
fs.rm(path[, options])
Removes files and directories (similar to POSIX rm).
File Stats
fs.stat(path[, options])
Retrieves file system statistics.
fs.lstat(path[, options])
Like stat() but returns info about symbolic link itself, not the target.
fs.fstat(fd[, options])
Returns stats for an open file descriptor.
Permissions and Ownership
fs.chmod(path, mode)
Changes file permissions.
fs.chown(path, uid, gid)
Changes file ownership.
Symbolic Links
fs.symlink(target, path[, type])
Creates a symbolic link.
fs.readlink(path[, options])
Reads the contents of a symbolic link.
fs.link(existingPath, newPath)
Creates a hard link.
File Streams
fs.createReadStream(path[, options])
Creates a readable stream.
fs.createWriteStream(path[, options])
Creates a writable stream.
FileHandle Class
TheFileHandle object is a wrapper for a numeric file descriptor.
Methods
filehandle.appendFile(data[, options])- Appends to filefilehandle.chmod(mode)- Changes permissionsfilehandle.chown(uid, gid)- Changes ownershipfilehandle.close()- Closes file handlefilehandle.read(buffer, offset, length, position)- Reads datafilehandle.readFile([options])- Reads entire filefilehandle.stat([options])- Gets file statsfilehandle.sync()- Flushes data to storagefilehandle.truncate(len)- Truncates filefilehandle.write(buffer, offset, length, position)- Writes datafilehandle.writeFile(data[, options])- Writes entire file
Properties
filehandle.fd- The numeric file descriptor
Performance Considerations
Sync vs Async vs Promises
- Synchronous: Blocks event loop - use only during app startup or in worker threads
- Callbacks: Best performance for high-throughput scenarios
- Promises: Modern, easier to use, slight overhead compared to callbacks
Streams for Large Files
Use streams instead ofreadFile()/writeFile() for large files to avoid memory issues:
Error Handling
Promise-based
Callback-based
Common Error Codes
EACCES- Permission deniedEEXIST- File already existsEISDIR- Is a directoryENOENT- No such file or directoryENOTDIR- Not a directoryENOTEMPTY- Directory not emptyEPERM- Operation not permitted
Best Practices
- Always close file handles when done
- Use promises API for modern async code
- Use streams for large files
- Avoid sync methods in production servers
- Handle errors appropriately
- Use
path.join()for cross-platform path handling - Set proper file permissions
- Use AbortSignal for cancellable operations