Node.js File System
The fs module reads and writes files. Prefer the promise version in modern code. This example uses a temporary folder.
ExampleNode.js
const fs = require("fs");
const os = require("os");
const path = require("path");
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "wecode-"));
const file = path.join(dir, "notes.txt");
fs.writeFileSync(file, "line one\n");
fs.appendFileSync(file, "line two\n");
console.log(fs.readFileSync(file, "utf8"));
console.log(fs.existsSync(file));
console.log(fs.statSync(file).size, "bytes");
console.log(fs.readdirSync(dir));
fs.promises.readFile(file, "utf8").then((text) => {
console.log(text.split("\n").length - 1, "lines");
fs.rmSync(dir, { recursive: true });
console.log(fs.existsSync(dir));
});Output
line one line two true 18 bytes [ 'notes.txt' ] 2 lines false
Quick check
Which fs function reads a whole file at once (synchronously)?
Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.
Tip: use the left and right arrow keys to move between lessons.