bugl
bugl
HomeLearnPatternsSearch
HomeLearnPatternsSearch

Loading lesson path

Learn/Node.js/Core Modules
Node.js•Core Modules

Node.js File System Module

Introduction to Node.js File System The Node.js File System module (fs) provides a comprehensive set of methods for working with the file system on your computer.

Formula

It allows you to perform file I/O operations in both synchronous and asynchronous ways.

Note:

The File System module is a core Node.js module, so no installation is required.

Importing the File System Module

You can import the File System module using CommonJS require() or ES modules import syntax: CommonJS (Default in Node.js)

const fs = require('fs');

Formula

ES Modules (Node.js 14 + with "type": "module" in package.json)
import fs from 'fs';

// Or for specific methods:

// import { readFile, writeFile } from 'fs/promises';

Promise-based API

Node.js provides promise-based versions of the File System API in the fs/promises namespace, which is recommended for modern applications: // Using promises (Node.js 10.0.0+)

const fs = require('fs').promises;
// Or with destructuring const { readFile, writeFile } = require('fs').promises;

// Or with ES modules

// import { readFile, writeFile } from 'fs/promises';

Common Use Cases

File Operations

Read and write files

Create and delete files

Append to files

Rename and move files

Change file permissions

Directory Operations

Create and remove directories

List directory contents

Watch for file changes

Get file/directory stats

Check file existence

Advanced Features

File streams

File descriptors

Symbolic links

File watching

Working with file permissions

Performance Tip:

For large files, consider using streams ( fs.createReadStream and fs.createWriteStream ) to avoid high memory usage.

Previous

Node.js HTTPS Module

Next

Node.js Path Module