Path Module
import path from "path"; path.basename("C:\\Users\\Chak\\Project\\file.md"); // => file.md (Will give the last part) path.basename("C:\\Users\\Chak\\Project\\file.md", ".md"); // => file (will remove extension) path.dirname("C:\\User\\Chak\\Project\\file.md"); // => "C:\\User\\Chak\\Project" (Removes file, gives directory) path.extname("C:\\User\\Chak\\Project\\file.md") // => .md (extension) path.join("C:", "Users", "chak", "Documents", "file.txt"); // => C:/Users/chak/Documents/file.txt (Construct file path) path.normalize("c:\\users\\\chak\\\\Documents\file.txt"); // => c:\users\chak\Documents\file.txt (Normalizes) path.parse("c:\\users\\chak\\Documents\\file.txt") // => { root: "C:\\", dir: "c:\\chak\\Documents", ... } (Get Details)
FS Module
It offers three variants:
- Promise based
- Callback based
- Synchronous based
Promise Based
import * as fs from "fs/promises"; // Creating Directory try { await fs.mkdir("C:/nodejs") console.log("Folder Created...") } catch { console.error(error); } // Creating a folder inside another folder that doesn't exist // This will give error if nodejs doesn't exist try { await fs.mkdir("C:/nodejs/main") console.log("Folder Created...") } catch { console.error(error); } // To fix this fs.mkdir("C:/nodejs/main", recursive: true)
Read Content of Directory
import * as fs from "fs/promises"; // Read the content try { const files = await fs.readdir("c:\\nodejs") for(const file of files){ console.log(file); } } catch (error) { console.log(error); }
Remove directory
import * as fs from "fs/promises"; // Only works if the directory is empty try { await fs.rmdir("C:/nodejs/courses"); } catch (error) { console.log(error) }
Create and write files (this replaces exiting)
await fs.writeFile("README.md", "Hello There");
Reading a file using fs.readFile() gives us buffer
To get the actual file contents and not the buffer
await fs.readFile("README.md", "utf-8");
Read a file, wrap it inside HTML and serve it
const fs = require("fs"); const template = require("./template"); fs.readFile("content.txt", "utf-8", (err, data) => { if (err) throw err; fs.writeFile("index.html", template(data), (err) => { if (err) throw err; }); });