Node.js fs Module
The fs (File System) module is a core built-in module in Node.js, used to interact with the file system.
The fs module provides a series of methods to handle file operations such as reading, writing, and deleting.
The fs module is one of the most commonly used modules in Node.js development, especially in scenarios where local files need to be processed.
How to use the fs module?
To use the fs module, you first need to import it:
const fs = require('fs');
Starting from Node.js 14, you can also use the ES6 import syntax:
Example
const fs = require('fs'); // CommonJS method
// or
import fs from 'fs'; // ES Module method
// or
import fs from 'fs'; // ES Module method
Main methods of the fs module
1. File Reading
Read file synchronously (readFileSync)
Example
const data = fs.readFileSync('example.txt', 'utf8');
console.log(data);
console.log(data);
'example.txt': the path of the file to be read'utf8': specify the encoding format (optional)- Synchronous methods block code execution until the file reading is complete
Read file asynchronously (readFile)
Example
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
if (err) throw err;
console.log(data);
});
- Asynchronous methods do not block code execution
- Handle results through callback functions
- Error-first callback is a common pattern in Node.js
2. File Writing
Write file synchronously (writeFileSync)
Example
fs.writeFileSync('output.txt', 'Hello, Node.js!');
Write file asynchronously (writeFile)
Example
fs.writeFile('output.txt', 'Hello, Node.js!', (err) => {
if (err) throw err;
console.log('File saved');
});
if (err) throw err;
console.log('File saved');
});
3. File Appending
Append synchronously (appendFileSync)
Example
fs.appendFileSync('log.txt', 'New log content\n');
Append asynchronously (appendFile)
Example
fs.appendFile('log.txt', 'New log content\n', (err) => {
if (err) throw err;
});
if (err) throw err;
});
4. File Status Check (stat)
Example
fs.stat('example.txt', (err, stats) => {
if (err) throw err;
console.log(`File size: ${stats.size} bytes`);
console.log(`Creation time: ${stats.birthtime}`);
console.log(`Whether it is a file: ${stats.isFile()}`);
console.log(`Whether it is a directory: ${stats.isDirectory()}`);
});
if (err) throw err;
console.log(`File size: ${stats.size} bytes`);
console.log(`Creation time: ${stats.birthtime}`);
console.log(`Whether it is a file: ${stats.isFile()}`);
console.log(`Whether it is a directory: ${stats.isDirectory()}`);
});
5. File Deletion
Delete synchronously (unlinkSync)
Example
fs.unlinkSync('fileToDelete.txt');
Delete asynchronously (unlink)
Example
fs.unlink('fileToDelete.txt', (err) => {
if (err) throw err;
console.log('File deleted');
});
if (err) throw err;
console.log('File deleted');
});
Promise and async/await Support
Node.js 10+ provides the fs/promises module, which supports Promise-style APIs:
Example
const fs = require('fs').promises;
async function readFile() {
try {
const data = await fs.readFile('example.txt', 'utf8');
console.log(data);
} catch (err) {
console.error('Error reading file:', err);
}
}
readFile();
async function readFile() {
try {
const data = await fs.readFile('example.txt', 'utf8');
console.log(data);
} catch (err) {
console.error('Error reading file:', err);
}
}
readFile();
Stream-based File Operations
For large files, using streams can improve performance:
Read Stream
Example
const readStream = fs.createReadStream('largeFile.txt', 'utf8');
readStream.on('data', (chunk) => {
console.log('Data received:', chunk.length);
});
readStream.on('end', () => {
console.log('Reading complete');
});
readStream.on('error', (err) => {
console.error('Reading error:', err);
});
readStream.on('data', (chunk) => {
console.log('Data received:', chunk.length);
});
readStream.on('end', () => {
console.log('Reading complete');
});
readStream.on('error', (err) => {
console.error('Reading error:', err);
});
Write Stream
Example
const writeStream = fs.createWriteStream('output.txt');
writeStream.write('First line of data\n');
writeStream.write('Second line of data\n');
writeStream.end('Last line of data');
writeStream.on('finish', () => {
console.log('Writing complete');
});
writeStream.on('error', (err) => {
console.error('Writing error:', err);
});
writeStream.write('First line of data\n');
writeStream.write('Second line of data\n');
writeStream.end('Last line of data');
writeStream.on('finish', () => {
console.log('Writing complete');
});
writeStream.on('error', (err) => {
console.error('Writing error:', err);
});
Directory Operations
Create Directory
Example
fs.mkdir('newFolder', (err) => {
if (err) throw err;
console.log('Directory created');
});
if (err) throw err;
console.log('Directory created');
});
Read Directory Contents
Example
fs.readdir('./', (err, files) => {
if (err) throw err;
console.log('Current directory contents:', files);
});
if (err) throw err;
console.log('Current directory contents:', files);
});
Delete Directory
Example
fs.rmdir('emptyFolder', (err) => {
if (err) throw err;
console.log('Directory deleted');
});
if (err) throw err;
console.log('Directory deleted');
});
Best Practices
- Prefer using asynchronous methods: avoid blocking the event loop
- Error handling: always handle possible errors
- Use streams to process large files: improve performance
- Path handling: use the path module to handle cross-platform path issues
- Permission checking: check file/directory permissions before operations
Practical Application Examples
File Copy Functionality
Example
const fs = require('fs');
function copyFile(source, target, cb) {
const readStream = fs.createReadStream(source);
const writeStream = fs.createWriteStream(target);
readStream.on('error', cb);
writeStream.on('error', cb);
readStream.on('close', () => {
writeStream.end();
cb(null);
});
readStream.pipe(writeStream);
}
copyFile('source.txt', 'target.txt', (err) => {
if (err) return console.error('Copy failed:', err);
console.log('File copied successfully');
});
function copyFile(source, target, cb) {
const readStream = fs.createReadStream(source);
const writeStream = fs.createWriteStream(target);
readStream.on('error', cb);
writeStream.on('error', cb);
readStream.on('close', () => {
writeStream.end();
cb(null);
});
readStream.pipe(writeStream);
}
copyFile('source.txt', 'target.txt', (err) => {
if (err) return console.error('Copy failed:', err);
console.log('File copied successfully');
});
Other Extensions
Node.js Built-in Modules