ELEVATE YOUR BUSINESS WITH

Limitless customization options & Elementor compatibility let anyone create a beautiful website with Valiance.

File System in NodeJs

SELECT * FROM `itio_tutorial_master` WHERE `tutorial_menu`='22' AND `tutorial_submenu`='1380' AND `tutorial_status`=1 LIMIT 1

File System in NodeJs

The File System (fs) module in Node.js lets you interact with the file system — reading, writing, updating, deleting files and directories — all using JavaScript.

It comes built-in, so no need to install anything.


✅ Importing the fs Module

js

const fs = require('fs/promises');


📖 Common File Operations

📄 1. Read a File (Async)

js

fs.readFile('example.txt', 'utf8', (err, data) => { if (err) throw err; console.log(data);});

✍️ 2. Write to a File (Async - Overwrites)

js

fs.writeFile('example.txt', 'Hello, World!', (err) => { if (err) throw err; console.log('File written!');});

➕ 3. Append to a File

js

fs.appendFile('example.txt', '\nThis is appended text.', (err) => { if (err) throw err; console.log('Content appended!');});

❌ 4. Delete a File

js

fs.unlink('example.txt', (err) => { if (err) throw err; console.log('File deleted!');});

📁 5. Create a Directory

js

fs.mkdir('myFolder', (err) => { if (err) throw err; console.log('Directory created!');});

📂 6. Read a Directory

js

fs.readdir('.', (err, files) => { if (err) throw err; console.log(files);});


🔄 Synchronous Versions

Every function also has a synchronous version with a Sync suffix:

js

const data = fs.readFileSync('example.txt', 'utf8');console.log(data);


🚀 Promise-based Usage (fs/promises)

js

const fs = require('fs/promises');async function run() { try { const data = await fs.readFile('example.txt', 'utf8'); console.log(data); } catch (err) { console.error(err); }}run();

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql