Node JS reading and writing files and driectories
In Node.js, file operations such as reading and writing files are handled using the built-in fs
(File System) module. This module provides both synchronous and asynchronous methods for interacting with the file system. Here’s a comprehensive guide on how to read and write files in Node.js:
1. Importing the fs
Module
To use the file system functions, you first need to import the fs
module:
const fs = require('fs');
2. Reading Files
Node.js provides several methods to read files:
2.1 Asynchronous File Reading
The asynchronous methods are non-blocking and allow your application to perform other tasks while waiting for the file operation to complete.
Using fs.readFile
:
const fs = require('fs');
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) {
console.error('Error reading file:', err);
return;
}
console.log('File contents:', data);
});
fs.readFile(path, encoding, callback)
:path
: Path to the file.encoding
: The encoding of the file (e.g., 'utf8'). If not provided, the file will be returned as a Buffer.callback
: A function that takes an error and the file data as arguments.
2.2 Synchronous File Reading
Synchronous methods block the execution until the file operation completes. They are generally used when you need to ensure that the file is read before continuing.
Using fs.readFileSync
:
const fs = require('fs');
try {
const data = fs.readFileSync('example.txt', 'utf8');
console.log('File contents:', data);
} catch (err) {
console.error('Error reading file:', err);
}
fs.readFileSync(path, encoding)
:path
: Path to the file.encoding
: The encoding of the file (e.g., 'utf8'). If not provided, the file will be returned as a Buffer.
3. Writing Files
Node.js also provides methods to write data to files:
3.1 Asynchronous File Writing
Using fs.writeFile
:
const fs = require('fs');
fs.writeFile('example.txt', 'Hello, world!', 'utf8', (err) => {
if (err) {
console.error('Error writing file:', err);
return;
}
console.log('File written successfully');
});
fs.writeFile(path, data, encoding, callback)
:path
: Path to the file.data
: Data to write to the file.encoding
: The encoding of the file (e.g., 'utf8'). Default is 'utf8'.callback
: A function that takes an error as an argument.
3.2 Synchronous File Writing
Using fs.writeFileSync
:
const fs = require('fs');
try {
fs.writeFileSync('example.txt', 'Hello, world!', 'utf8');
console.log('File written successfully');
} catch (err) {
console.error('Error writing file:', err);
}
fs.writeFileSync(path, data, encoding)
:path
: Path to the file.data
: Data to write to the file.encoding
: The encoding of the file (e.g., 'utf8'). Default is 'utf8'.
4. Appending to Files
To append data to a file, you can use fs.appendFile
(asynchronous) or fs.appendFileSync
(synchronous).
Using fs.appendFile
:
const fs = require('fs');
fs.appendFile('example.txt', 'Appended text\n', 'utf8', (err) => {
if (err) {
console.error('Error appending to file:', err);
return;
}
console.log('Data appended successfully');
});
fs.appendFile(path, data, encoding, callback)
:path
: Path to the file.data
: Data to append to the file.encoding
: The encoding of the file (e.g., 'utf8'). Default is 'utf8'.callback
: A function that takes an error as an argument.
Using fs.appendFileSync
:
const fs = require('fs');
try {
fs.appendFileSync('example.txt', 'Appended text\n', 'utf8');
console.log('Data appended successfully');
} catch (err) {
console.error('Error appending to file:', err);
}
fs.appendFileSync(path, data, encoding)
:path
: Path to the file.data
: Data to append to the file.encoding
: The encoding of the file (e.g., 'utf8'). Default is 'utf8'.
5. Deleting Files
To delete files, use fs.unlink
(asynchronous) or fs.unlinkSync
(synchronous).
Using fs.unlink
:
const fs = require('fs');
fs.unlink('example.txt', (err) => {
if (err) {
console.error('Error deleting file:', err);
return;
}
console.log('File deleted successfully');
});
fs.unlink(path, callback)
:path
: Path to the file.callback
: A function that takes an error as an argument.
Using fs.unlinkSync
:
const fs = require('fs');
try {
fs.unlinkSync('example.txt');
console.log('File deleted successfully');
} catch (err) {
console.error('Error deleting file:', err);
}
fs.unlinkSync(path)
:path
: Path to the file.
6. Handling Directories
Node.js also provides methods to handle directories:
Creating a Directory:
const fs = require('fs');
fs.mkdir('myDirectory', (err) => {
if (err) {
console.error('Error creating directory:', err);
return;
}
console.log('Directory created successfully');
});
Reading Directory Contents:
const fs = require('fs');
fs.readdir('myDirectory', (err, files) => {
if (err) {
console.error('Error reading directory:', err);
return;
}
console.log('Files in directory:', files);
});
Deleting a Directory:
const fs = require('fs');
fs.rmdir('myDirectory', (err) => {
if (err) {
console.error('Error deleting directory:', err);
return;
}
console.log('Directory deleted successfully');
});
Summary
- Reading Files: Use
fs.readFile
(asynchronous) orfs.readFileSync
(synchronous). - Writing Files: Use
fs.writeFile
(asynchronous) orfs.writeFileSync
(synchronous). - Appending Files: Use
fs.appendFile
(asynchronous) orfs.appendFileSync
(synchronous). - Deleting Files: Use
fs.unlink
(asynchronous) orfs.unlinkSync
(synchronous). - Handling Directories: Use
fs.mkdir
,fs.readdir
, andfs.rmdir
for directory operations.