Node.js File System and Path: Read, Write and Organise Files
Test automation is full of files: JSON and CSV test data, environment configs, screenshots, downloaded reports and logs. Node.js handles them with two built-in modules: fs (file system) reads, writes, lists and deletes files and folders, and path builds file paths that work on Windows, macOS and Linux. In this lesson you will use the modern promise-based fs/promises API, read and write JSON, create and clean output folders, load CSV test data and stream large log files. Every example writes into its own working folder, so the outputs below are real.
📖 What You’ll Learn: the fs/promises API, reading and writing text files, appending, reading and writing JSON, creating folders with recursive: true, listing folders, file information with stat, checking whether a file exists, deleting files and folders, the path module (join, resolve, basename, extname, dirname, parse), __dirname vs process.cwd(), reading CSV test data, streaming large files line by line, and cleaning up test artefacts.
📁 The fs Module: Three Styles
Definition: fs is Node.js’s built-in module for working with the file system. It is not available in browsers, only in Node.js. It offers each operation in three styles:
| Style | Import | Example | Use it for |
|---|---|---|---|
| Promises (recommended) | require("node:fs/promises") | await fs.readFile(p, "utf8") | Almost everything |
| Synchronous | require("node:fs") | fs.readFileSync(p, "utf8") | Small startup scripts and config loading |
| Callbacks (oldest) | require("node:fs") | fs.readFile(p, "utf8", cb) | Older code you have to maintain |
The node: prefix marks a built-in module, so it can never be confused with an npm package of the same name. The examples use CommonJS; in an ES module write import fs from "node:fs/promises".
📝 Reading and Writing Text Files
writeFile creates the file, or replaces its contents if it already exists. appendFile adds to the end. readFile with the "utf8" encoding returns a string; without an encoding it returns a raw Buffer.
📄 text.js
const fs = require("node:fs/promises");
async function main() {
await fs.writeFile("notes.txt", "Smoke tests: passed\n");
await fs.appendFile("notes.txt", "Regression: 2 failures\n");
const text = await fs.readFile("notes.txt", "utf8");
console.log(text);
console.log("lines:", text.trim().split("\n").length);
const raw = await fs.readFile("notes.txt"); // no encoding -> Buffer
console.log(raw.constructor.name, raw.length, "bytes");
}
main();
⌨️ Terminal
node text.js
🖥️ Output
Smoke tests: passed
Regression: 2 failures
lines: 2
Buffer 43 bytes
Reading a file that does not exist rejects with an error whose code is ENOENT (“Error NO ENTry”). Check error.code to give a clear message:
📄 missing.js
const fs = require("node:fs/promises");
async function readConfig(file) {
try {
return await fs.readFile(file, "utf8");
} catch (error) {
if (error.code === "ENOENT") throw new Error(`Config file "${file}" not found. Did you create it?`);
throw error;
}
}
readConfig("staging.json").catch((e) => console.log(e.message));
⌨️ Terminal
node missing.js
🖥️ Output
Config file "staging.json" not found. Did you create it?
| Error code | Meaning |
|---|---|
ENOENT | The file or folder does not exist |
EEXIST | It already exists (for example mkdir without recursive) |
EACCES / EPERM | No permission, or the file is locked (common on Windows when a file is open) |
EISDIR | You used a folder where a file was expected |
ENOTEMPTY | You tried to remove a folder that still has files in it |
🗂️ Reading and Writing JSON
JSON files are text: read the text, then JSON.parse it. To save, JSON.stringify(data, null, 2) gives readable two-space indentation. These two helpers appear in almost every test framework:
📄 json.js
const fs = require("node:fs/promises");
async function readJSON(file) {
return JSON.parse(await fs.readFile(file, "utf8"));
}
async function writeJSON(file, data) {
await fs.writeFile(file, JSON.stringify(data, null, 2) + "\n");
}
async function main() {
await writeJSON("users.json", [
{ email: "admin@sqatools.in", role: "admin" },
{ email: "tester@sqatools.in", role: "tester" },
]);
const users = await readJSON("users.json");
users.push({ email: "viewer@sqatools.in", role: "viewer" });
await writeJSON("users.json", users);
console.log(await fs.readFile("users.json", "utf8"));
}
main();
⌨️ Terminal
node json.js
🖥️ Output
[
{
"email": "admin@sqatools.in",
"role": "admin"
},
{
"email": "tester@sqatools.in",
"role": "tester"
},
{
"email": "viewer@sqatools.in",
"role": "viewer"
}
]
💡 Tip: For small static data you can also use require("./users.json"). It parses the file once and caches it, so changes made to the file later in the same run are not seen. Use readFile + JSON.parse when the file can change.
📂 Folders: Create, List, Inspect and Delete
📄 folders.js
const fs = require("node:fs/promises");
async function main() {
// recursive: true creates parent folders and does not fail if the folder exists
await fs.mkdir("reports/2026-11-23/screenshots", { recursive: true });
await fs.writeFile("reports/2026-11-23/summary.txt", "18 passed, 2 failed");
await fs.writeFile("reports/2026-11-23/screenshots/login-failed.png", "fake image bytes");
console.log(await fs.readdir("reports/2026-11-23"));
const entries = await fs.readdir("reports/2026-11-23", { withFileTypes: true });
for (const e of entries) console.log(e.isDirectory() ? "dir " : "file", e.name);
const info = await fs.stat("reports/2026-11-23/summary.txt");
console.log("size:", info.size, "bytes, is file:", info.isFile());
const all = await fs.readdir("reports", { recursive: true }); // every nested entry
console.log(all.length, "entries in total");
await fs.rm("reports", { recursive: true, force: true }); // delete the whole tree
console.log("still there?", await fs.readdir(".").then((names) => names.includes("reports")));
}
main();
⌨️ Terminal
node folders.js
🖥️ Output
[ 'screenshots', 'summary.txt' ]
dir screenshots
file summary.txt
size: 19 bytes, is file: true
4 entries in total
still there? false
| Function | Does |
|---|---|
mkdir(p, { recursive: true }) | Create a folder and any missing parents |
readdir(p) | List names in a folder (withFileTypes for file/folder info, recursive for subfolders) |
stat(p) | Size, dates, isFile(), isDirectory() |
rename(from, to) | Rename or move a file |
copyFile(from, to) / cp(from, to, { recursive: true }) | Copy a file / a folder |
unlink(p) | Delete one file |
rm(p, { recursive: true, force: true }) | Delete a folder tree; force ignores “does not exist” |
⚠️ Watch out: fs.rm(p, { recursive: true, force: true }) deletes without asking and without a recycle bin. Build the path from a known output folder, never from user input, and double-check it before running cleanup code.
Does a file exist?
Use existsSync for a quick check. With promises, try the operation you actually want and handle ENOENT. That avoids a race where the file disappears between the check and the use.
📄 exists.js
const { existsSync } = require("node:fs");
const fs = require("node:fs/promises");
async function main() {
console.log(existsSync("baseline.png"));
await fs.writeFile("baseline.png", "pixels");
console.log(existsSync("baseline.png"));
const exists = await fs.access("missing.png").then(() => true, () => false);
console.log("missing.png exists:", exists);
}
main();
⌨️ Terminal
node exists.js
🖥️ Output
false
true
missing.png exists: false
🧭 The path Module
Windows uses \ between folder names and macOS and Linux use /. Build paths with path instead of gluing strings together, and the same code works everywhere. The output below was produced on Windows; on macOS and Linux the separators are /:
📄 paths.js
const path = require("node:path");
const file = path.join("reports", "2026-11-23", "..", "latest", "summary.json");
console.log("join: ", file);
console.log("basename: ", path.basename(file));
console.log("name only:", path.basename(file, ".json"));
console.log("extname: ", path.extname(file));
console.log("dirname: ", path.dirname(file));
console.log("parse: ", path.parse(file));
console.log("sep: ", path.sep);
⌨️ Terminal
node paths.js
🖥️ Output (Windows)
join: reports\latest\summary.json
basename: summary.json
name only: summary
extname: .json
dirname: reports\latest
parse: {
root: '',
dir: 'reports\\latest',
base: 'summary.json',
ext: '.json',
name: 'summary'
}
sep: \
Notice that join also cleaned up the ... To see both styles from any machine, use path.posix and path.win32 explicitly:
📄 both.js
const path = require("node:path");
console.log(path.posix.join("test-data", "users", "admin.json"));
console.log(path.win32.join("test-data", "users", "admin.json"));
console.log(path.posix.extname("report.final.html"));
⌨️ Terminal
node both.js
🖥️ Output
test-data/users/admin.json
test-data\users\admin.json
.html
Absolute paths: resolve, __dirname and process.cwd()
process.cwd()is the folder you started Node.js from. It changes depending on where you run the command.__dirname(CommonJS) orimport.meta.dirname(ES modules) is the folder that contains the current file. It never changes.path.resolve(...parts)turns parts into an absolute path, starting fromprocess.cwd().
📄 where.js
const path = require("node:path");
console.log("cwd: ", process.cwd());
console.log("__dirname:", __dirname);
console.log("resolve: ", path.resolve("test-data", "users.json"));
console.log("safe path:", path.join(__dirname, "test-data", "users.json"));
⌨️ Terminal
node where.js
🖥️ Output (Windows)
cwd: C:\Users\you\js-course
__dirname: C:\Users\you\js-course
resolve: C:\Users\you\js-course\test-data\users.json
safe path: C:\Users\you\js-course\test-data\users.json
💡 Tip: Load test data with path.join(__dirname, "test-data", "users.json"), not with a plain relative path like "test-data/users.json". A relative path depends on the folder the tests were started from, which is a classic reason why tests pass locally and fail in CI or an IDE.
📊 Reading CSV Test Data
CSV is a popular format for data-driven tests because testers can edit it in Excel or Google Sheets. For simple files (no commas or line breaks inside values) splitting lines and commas is enough. For real-world CSV with quoted values, use a library such as csv-parse.
📄 test-data/logins.csv
email,password,expected
admin@sqatools.in,Admin#123,dashboard
locked@sqatools.in,Locked#123,account locked
wrong@sqatools.in,nope,invalid credentials
📄 csv.js
const fs = require("node:fs/promises");
const path = require("node:path");
async function readCsv(file) {
const text = await fs.readFile(file, "utf8");
const [headerLine, ...lines] = text.trim().split(/\r?\n/);
const headers = headerLine.split(",");
return lines.map((line) => {
const values = line.split(",");
return Object.fromEntries(headers.map((h, i) => [h, values[i]]));
});
}
async function main() {
const rows = await readCsv(path.join(__dirname, "test-data", "logins.csv"));
console.log(rows);
for (const row of rows) {
console.log(`test: login as ${row.email} -> expect ${row.expected}`);
}
}
main();
⌨️ Terminal
node csv.js
🖥️ Output
[
{
email: 'admin@sqatools.in',
password: 'Admin#123',
expected: 'dashboard'
},
{
email: 'locked@sqatools.in',
password: 'Locked#123',
expected: 'account locked'
},
{
email: 'wrong@sqatools.in',
password: 'nope',
expected: 'invalid credentials'
}
]
test: login as admin@sqatools.in -> expect dashboard
test: login as locked@sqatools.in -> expect account locked
test: login as wrong@sqatools.in -> expect invalid credentials
The /\r?\n/ split handles files saved on Windows (CRLF line endings) as well as macOS and Linux (LF).
🌊 Large Files: Streams and Reading Line by Line
readFile loads the whole file into memory. That is fine for configs and test data, but a log file of several gigabytes needs a stream, which reads it in small chunks. readline turns a stream into lines you can loop over with for await:
📄 log-scan.js
const fs = require("node:fs");
const readline = require("node:readline");
async function main() {
const lines = ["INFO start", "ERROR timeout on /api/cart", "INFO retry", "ERROR 500 on /api/pay", "INFO done"];
fs.writeFileSync("run.log", lines.join("\n") + "\n");
const rl = readline.createInterface({ input: fs.createReadStream("run.log", "utf8"), crlfDelay: Infinity });
let lineNo = 0;
const errors = [];
for await (const line of rl) {
lineNo++;
if (line.startsWith("ERROR")) errors.push(`line ${lineNo}: ${line}`);
}
console.log(`${errors.length} errors found`);
errors.forEach((e) => console.log(e));
}
main();
⌨️ Terminal
node log-scan.js
🖥️ Output
2 errors found
line 2: ERROR timeout on /api/cart
line 4: ERROR 500 on /api/pay
fs.createWriteStream(file) is the writing counterpart: call .write() many times and .end() when finished, which is ideal for writing a long log during a test run.
🧪 Tester Scenario: A Results Folder for Every Run
This helper creates a timestamped results folder, saves a JSON summary and a failure log, keeps only the newest runs and prints what is on disk. It is the same idea Playwright uses for test-results/ and playwright-report/.
📄 results.js
const fs = require("node:fs/promises");
const path = require("node:path");
const ROOT = path.join(__dirname, "results");
async function saveRun(runId, results) {
const dir = path.join(ROOT, runId);
await fs.mkdir(dir, { recursive: true });
const failed = results.filter((r) => r.status === "failed");
const summary = { runId, total: results.length, passed: results.length - failed.length, failed: failed.length };
await fs.writeFile(path.join(dir, "summary.json"), JSON.stringify(summary, null, 2));
if (failed.length) {
await fs.writeFile(path.join(dir, "failures.log"), failed.map((f) => `${f.name}: ${f.error}`).join("\n"));
}
return summary;
}
async function keepNewest(count) {
const runs = (await fs.readdir(ROOT)).sort(); // names sort by time
const old = runs.slice(0, Math.max(0, runs.length - count));
for (const name of old) await fs.rm(path.join(ROOT, name), { recursive: true, force: true });
return old;
}
async function main() {
const results = [
{ name: "login works", status: "passed" },
{ name: "cart total", status: "failed", error: "expected 998, got 999" },
{ name: "logout", status: "passed" },
];
for (const runId of ["2026-11-21_0900", "2026-11-22_0900", "2026-11-23_0900"]) {
console.log(await saveRun(runId, results));
}
console.log("removed:", await keepNewest(2));
console.log("kept:", await fs.readdir(ROOT));
console.log(await fs.readdir(path.join(ROOT, "2026-11-23_0900")));
console.log(await fs.readFile(path.join(ROOT, "2026-11-23_0900", "failures.log"), "utf8"));
}
main();
⌨️ Terminal
node results.js
🖥️ Output
{ runId: '2026-11-21_0900', total: 3, passed: 2, failed: 1 }
{ runId: '2026-11-22_0900', total: 3, passed: 2, failed: 1 }
{ runId: '2026-11-23_0900', total: 3, passed: 2, failed: 1 }
removed: [ '2026-11-21_0900' ]
kept: [ '2026-11-22_0900', '2026-11-23_0900' ]
[ 'failures.log', 'summary.json' ]
cart total: expected 998, got 999
📝 Practice Questions with Answers
Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.
Q1. Write hello.txt with the text “Hello, QA!”, read it back and print it in upper case.
Show answer
📄 practice1.js
const fs = require("node:fs/promises");
async function main() {
await fs.writeFile("hello.txt", "Hello, QA!");
const text = await fs.readFile("hello.txt", "utf8");
console.log(text.toUpperCase());
}
main();🖥️ Output
HELLO, QA!Q2. Read config.json ({"baseURL":"https://staging.example.com","retries":1}), change retries to 3 and save it with two-space indentation.
Show answer
📄 config.json
{"baseURL":"https://staging.example.com","retries":1}📄 practice2.js
const fs = require("node:fs/promises");
async function main() {
const config = JSON.parse(await fs.readFile("config.json", "utf8"));
config.retries = 3;
await fs.writeFile("config.json", JSON.stringify(config, null, 2));
console.log(await fs.readFile("config.json", "utf8"));
}
main();🖥️ Output
{
"baseURL": "https://staging.example.com",
"retries": 3
}Q3. Create the folder output/screenshots in one call (even though output does not exist), then list the contents of output.
Show answer
📄 practice3.js
const fs = require("node:fs/promises");
async function main() {
await fs.mkdir("output/screenshots", { recursive: true });
console.log(await fs.readdir("output"));
}
main();🖥️ Output
[ 'screenshots' ]Q4. Using only path, get the file name without extension and the extension from "downloads/invoice-2026-11.pdf".
Show answer
📄 practice4.js
const path = require("node:path");
const file = "downloads/invoice-2026-11.pdf";
const ext = path.extname(file);
console.log(path.basename(file, ext), ext);🖥️ Output
invoice-2026-11 .pdfQ5. Write safeRead(file) that returns the file’s text, or null when the file does not exist, and rethrows any other error.
Show answer
📄 practice5.js
const fs = require("node:fs/promises");
async function safeRead(file) {
try {
return await fs.readFile(file, "utf8");
} catch (e) {
if (e.code === "ENOENT") return null;
throw e;
}
}
async function main() {
await fs.writeFile("a.txt", "data");
console.log(await safeRead("a.txt"), await safeRead("nope.txt"));
}
main();🖥️ Output
data nullQ6. Count how many .png files are in a screenshots folder that also contains other files.
Show answer
📄 practice6.js
const fs = require("node:fs/promises");
const path = require("node:path");
async function main() {
await fs.mkdir("screenshots", { recursive: true });
for (const f of ["home.png", "cart.png", "notes.txt", "login.PNG"]) await fs.writeFile(path.join("screenshots", f), "");
const files = await fs.readdir("screenshots");
const pngs = files.filter((f) => path.extname(f).toLowerCase() === ".png");
console.log(pngs.length, pngs);
}
main();🖥️ Output
3 [ 'cart.png', 'home.png', 'login.PNG' ]🧠 MCQ Quiz: File System and Path
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
- Which import gives the promise-based fs API?Answer: require(“node:fs/promises”). Then use await fs.readFile(…).
- What does
fs.readFile(p, "utf8")resolve to?Answer: A string. Without an encoding you get a Buffer. - Which error code means “file not found”?Answer: ENOENT. Check error.code === “ENOENT”.
- What does
{ recursive: true }do infs.mkdir?Answer: Creates missing parent folders and does not fail if the folder exists. Very handy for output folders. - What does
fs.writeFiledo when the file already exists?Answer: Replaces its contents. Use appendFile to add to the end. - Why use
path.joininstead of “a” + “/” + “b”?Answer: It uses the right separator for the OS and normalises the path. It also resolves “.” and “..”. - What is
path.extname("report.final.html")?Answer: “.html”. Only the last extension, including the dot. - What is the difference between
__dirnameandprocess.cwd()?Answer: __dirname is the folder of the current file; cwd is where Node.js was started. Use __dirname (or import.meta.dirname) to find files next to your code. - How do you delete a folder and everything inside it?Answer: fs.rm(p, { recursive: true, force: true }). unlink removes a single file.
- When should you read a file with a stream instead of readFile?Answer: When it is very large, such as a multi-GB log. Streams read in chunks instead of loading everything into memory.
💼 Interview Questions and Answers
Q1. How do you read test data from a JSON or CSV file in a Node.js test framework?
Build the path from the test file’s folder (path.join(__dirname, "test-data", "users.json")) so it does not depend on where the runner was started. For JSON, JSON.parse(await fs.readFile(p, "utf8")). For CSV, split simple files by lines and commas, or use a parser such as csv-parse for quoted values. Then loop over the rows to generate one test per row (data-driven testing).
Q2. Sync vs async fs functions: when would you use each?
Async (fs/promises) does not block the event loop, so it is the default for anything that runs during tests or in a server. Sync functions (readFileSync) are acceptable in short scripts or for loading configuration once at startup, where blocking for a few milliseconds does not matter and the code is simpler.
Q3. Why do tests sometimes find a file locally but not in CI?
Usually a relative path: it is resolved against process.cwd(), which differs between a terminal, an IDE and a CI job. Other causes are case sensitivity (Linux CI treats Users.json and users.json as different files, Windows does not), hard-coded \ separators, and files that are git-ignored and so never reach CI. Fix it with path.join(__dirname, ...) and matching file-name case.
Q4. How would you clean up test artefacts safely?
Write all artefacts into one known output folder built from the project root, delete it (or old runs inside it) with fs.rm(dir, { recursive: true, force: true }) at the start of a run, and keep the latest results for debugging. Never delete paths built from user input or environment variables without validating them.
❓ Frequently Asked Questions
🤔 Can I use fs in the browser?
No. Browsers do not give web pages access to the file system. Use file inputs, downloads, or the browser storage APIs covered in the DOM module.
🤔 What is a Buffer?
A Buffer holds raw binary data. readFile without an encoding returns one, which you need for images, PDFs and other binary files. buffer.toString("utf8") converts text bytes to a string.
🤔 Should I use fs.exists?
The callback fs.exists is deprecated. Use existsSync for a quick check, or just try the operation and handle ENOENT.
🤔 How do I watch a folder for changes?
Use fs.watch(path, callback), or the --watch flag (node --watch app.js) to restart a script when its files change.
🏁 Summary
- Use
require("node:fs/promises")andawaitfor file work; sync functions only for simple scripts. readFile/writeFile/appendFilefor text, plusJSON.parse/JSON.stringifyfor JSON.mkdirwithrecursive,readdir,statandrmwithrecursivemanage folders; checkerror.code(such asENOENT) for clear errors.- Build paths with
path.joinand anchor them to__dirname(orimport.meta.dirname) so tests work from any folder and OS. - Stream large files with
createReadStreamandreadlineinstead of loading them whole.
Next, continue with Lesson 55: Environment Variables.
🎬 Watch JavaScript and automation tutorials on YouTube!
Subscribe to SqaToolsByDY • Practice on sqatools.in