1.File System
CommonJS (CJS) vs. ECMAScript Modules (ESM)
CommonJS Syntax
- Importing Modules:
- To use a module, assign it to a constant:
const fs = require('fs');
- To use a module, assign it to a constant:
File System Operations
Using the fs module, you can perform various file operations:
-
Write to a File:
fs.writeFile('hey.txt', "helloworld", function(err) { if (err) console.error(err); else console.log("File written successfully."); }); -
Append to a File:
fs.appendFile("hey.txt", " this is new", function(err) { if (err) console.error(err); else console.log("Content appended successfully."); }); -
Rename a File:
fs.rename("hey.txt", "hello.txt", function(err) { if (err) console.error(err); else console.log("File renamed successfully."); }); -
Copy a File:
- To copy a file, you can use
fs.copyFile(Node.js 8.5.0 and above):
fs.copyFile('source.txt', 'destination.txt', (err) => { if (err) console.error(err); else console.log('File copied successfully.'); }); - To copy a file, you can use
-
Delete a File (Unlink):
fs.unlink("hello.txt", function(err) { if (err) console.error(err); else console.log("File deleted successfully."); });
6. Delete a Directory
-
Removing an Empty Directory:
fs.rmdir("./foldername", function(err) { if (err) console.log(err); else console.log("Directory removed successfully."); });- Note:
fs.rmdircannot remove directories that contain files. Attempting to do so will result in an error.
- Note:
-
Removing a Directory Recursively:
- To delete a directory along with its contents (files and subdirectories), use
fs.rmwith therecursiveoption:
fs.rm("./foldername", { recursive: true }, function(err) { if (err) console.log(err); else console.log("Directory and its contents removed successfully."); });- Note: The default value for
recursiveisfalse, so you must specify it astruefor recursive deletion.
- To delete a directory along with its contents (files and subdirectories), use
7. Create a Folder
- To create a new directory:
fs.mkdir("./newFolder", { recursive: true }, function(err) { if (err) console.log(err); else console.log("Directory created successfully."); });- The
recursive: trueoption allows the creation of nested directories without error if the parent directory already exists.
- The
8. Read a File
- To read the contents of a file:
fs.readFile('file.txt', 'utf8', function(err, data) { if (err) console.log(err); else console.log(data); // Displays the content of the file });
9. Read Folder Contents
- To read the contents of a directory:
fs.readdir('./foldername', function(err, files) { if (err) console.log(err); else { console.log("Directory contents:"); files.forEach(file => { console.log(file); }); } });