Node.js File System (fs Module)
After completing this topic
You will be able to write code to read, write, and delete files in Node.js.
Things you can't do in a browser
JavaScript in the browser cannot access files on your computer for security reasons. However, since Node.js is a server-side environment, you can freely read and write files. The fs (File System) module provides this functionality.
// Import the fs module
const fs = require("fs");
// Read a file (synchronous method β pauses until reading is complete)
const data = fs.readFileSync("memo.txt", "utf8");
console.log(data);require("fs") is the way to import built-in modules in Node.js. No separate installation is required. If you omit "utf8", a Buffer (binary data) will be returned, and you will see numbers instead of characters.
Writing and Appending to Files
const fs = require("fs");
// Write to a file β creates the file if it doesn't exist, overwrites it if it does
fs.writeFileSync("output.txt", "First line\n");
// Append content to a file (does not overwrite)
fs.appendFileSync("output.txt", "Second line\n");
// Check
const result = fs.readFileSync("output.txt", "utf8");
console.log(result);
// First line
// Second linewriteFileSync completely overwrites the existing content. To preserve the existing content while adding new content, use appendFileSync.
Checking for and Deleting Files
const fs = require("fs");
// Check if a file exists
if (fs.existsSync("output.txt")) {
console.log("The file exists");
// Delete the file
fs.unlinkSync("output.txt");
console.log("Deleted");
}
// Create a directory (folder)
if (!fs.existsSync("logs")) {
fs.mkdirSync("logs");
}
// List files in a directory
const files = fs.readdirSync(".");
console.log(files); // ["index.js", "logs", ...]All the methods used here have Sync (synchronous) attached. The code execution will pause until the file operation is complete. In a real server environment, the asynchronous versions (readFile, writeFile β no Sync) are used, which is covered in Synchronous vs. Asynchronous.