NodeJS by Example: File System
|
The File System module (fs) provides APIs for interacting with the file system. Node.js offers both callback-based and promise-based APIs. We'll focus on the modern promises API. |
|
|
Import the promises API from the fs module. This provides async/await compatible functions. |
|
|
Reading Files readFile reads the entire contents of a file. Specify encoding to get a string, otherwise you get a Buffer. |
|
|
Writing Files writeFile creates a new file or overwrites an existing one. You can specify encoding and file mode. |
|
|
File Information stat returns information about a file: size, timestamps, and whether it's a file or directory. |
|
|
Checking File Existence Use existsSync for simple existence checks, or access() for permission checks. |
|
|
Creating Directories mkdir creates directories. Use recursive: true to create nested directories. |
|
|
Reading Directories readdir lists the contents of a directory. Use withFileTypes for more details. |
|
|
Renaming and Moving Files rename can rename or move files and directories. |
|
|
Copying Files copyFile creates a copy of a file. |
|
|
Deleting Files unlink removes files. For directories, use rmdir or rm with recursive option. |
|
|
Complete Example Here's a practical example that combines multiple operations. |
|
|
Create a test file first |
|
|
Run the file system example |
|