L3. File Handling in Node.js

2 min read
console.log("File Handling");
1. File System Module (fs/promises)
Asynchronous File System Operations using promises.
Import necessary functions:
import { readFile, writeFile, appendFile, mkdir } from "fs/promises";
Functions and their uses:
readFile
→ Reads data from an existing file.writeFile
→ Creates a new file and writes data into it.appendFile
→ Adds data to an existing file.mkdir
→ Creates a new folder (directory).
2. Reading a File
const read_file = async (filename) => {
const data = await readFile(filename, "utf-8");
console.log(data);
};
Calling the Function:
read_file("sample.txt");
Reads
sample.txt
and logs the content."utf-8"
ensures proper text encoding.
3. Creating a File & Writing Data
const create_file = async (filename, content) => {
await writeFile(filename, content);
console.log("File created");
};
Calling the Function:
create_file("AI.txt", "This is a testing file");
- Creates
AI.txt
and writes"This is a testing file"
inside it.
4. Appending Data to a File
const append_file = async (filename, content) => {
await appendFile(filename, content);
console.log("Data appended");
};
Calling the Function:
append_file("AI.txt", " This is additional data");
- Adds
"This is additional data"
toAI.txt
.
5. Creating a Folder (Directory)
const create_dir = async (dirname) => {
await mkdir(dirname, { recursive: true });
console.log("Folder created");
};
recursive: true
→ Allows creating nested directories.
Calling the Function:
create_dir("components"); // Creates a folder named "components"
create_dir("AI/sub"); // Creates a subfolder inside "AI"
0
Subscribe to my newsletter
Read articles from Sahana S Acharya directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
