Node Process and OS Details, File Paths and Reading Files
The process and os modules (versions, platform, memory, CPUs, timing), how the fs module is organized (callback, Sync, promise, file descriptor and FileHandle variants), building and checking paths safely with node:path, and reading files whole, line by line or by byte range.
kvi5hnuCode Sprout team member6 min readOn this page
This article starts the file system part of Node: first the information Node gives you about the running process and machine, then how the large fs API is organized, how to work with paths, and the three ways to read a file.
The process and the machine
The global process object describes the running program. Besides argv, env, exit and the events covered in article 122, useful members include:
| Member | Gives you |
|---|---|
process.version, process.versions | Node's version ("v24.11.0"), and versions of V8, libuv, OpenSSL and others |
process.platform, process.arch | "linux", "darwin", "win32"; "x64", "arm64" |
process.pid, process.ppid | this process's ID and its parent's ID |
process.cwd(), process.chdir(dir) | the current working directory |
process.memoryUsage() | rss, heapTotal, heapUsed, external, arrayBuffers in bytes |
process.cpuUsage(), process.resourceUsage() | CPU time used, and more detailed resource counters |
process.uptime() | seconds since the process started |
process.hrtime.bigint() | a nanosecond clock as a BigInt, for measuring durations (or use performance.now()) |
process.stdin, stdout, stderr | the standard streams (articles 126 and 127) |
The node:os module describes the computer: os.cpus() and os.availableParallelism() (how many threads can run in parallel, useful for sizing worker pools), os.totalmem() and os.freemem(), os.homedir(), os.tmpdir(), os.hostname(), os.platform(), os.release(), os.uptime(), os.loadavg(), os.networkInterfaces(), os.userInfo() and os.EOL ("\n", or "\r\n" on Windows).
const os = require("node:os");
const mem = process.memoryUsage();
console.log({
nodeVersion: /^v\d+\.\d+\.\d+$/.test(process.version),
platform: ["linux", "darwin", "win32"].includes(process.platform),
pidIsNumber: Number.isInteger(process.pid),
heapUsedMB: mem.heapUsed / 1024 / 1024 < 100,
cpus: os.availableParallelism() >= 1,
sameHome: os.homedir() === os.userInfo().homedir,
});
const t0 = process.hrtime.bigint();
let x = 0;
for (let i = 0; i < 1e6; i++) x += i;
const elapsedNs = process.hrtime.bigint() - t0;
console.log(typeof elapsedNs, elapsedNs > 0n, x);
{
nodeVersion: true,
platform: true,
pidIsNumber: true,
heapUsedMB: true,
cpus: true,
sameHome: true
}
bigint true 499999500000
The example prints checks rather than raw values, which differ from machine to machine.
How the fs module is organized
node:fs is large because most operations come in several variants:
- Callback:
fs.readFile(path, cb), the original style. - Sync:
fs.readFileSync(path), blocking; for scripts and startup code (article 123). - Promise:
readFilefromnode:fs/promises(also available asfs.promises). The best default for application code. - File descriptor: a descriptor is an integer the operating system uses to refer to an open file. Functions with an
fprefix take one instead of a path:fs.fstat(fd),fs.ftruncate(fd). - FileHandle: the promise API's object wrapper around a file descriptor, returned by
fsp.open(). - Functions with an
lprefix, such aslstatandlchown, act on a symbolic link itself instead of following it.
Many names come from Unix system calls: deleting a file is unlink, and changing permissions is chmod.
Paths
A path names a file: absolute (/home/ada/notes.txt, C:\Users\ada\notes.txt) or relative to the current working directory, process.cwd(). Relative paths depend on where the program was started from, not on where your code lives, which is a common source of "file not found" bugs. For a file next to your code, build the path from the module's own directory:
- CommonJS:
path.join(__dirname, "data.json") - ES modules:
path.join(import.meta.dirname, "data.json"), ornew URL("./data.json", import.meta.url), whichfsfunctions also accept.
Don't build paths by string concatenation. node:path handles separators, . and .. segments, and duplicate slashes (output shown for macOS and Linux):
const path = require("node:path");
const p = "src/pkg/report.test.js";
console.log(path.basename(p), path.extname(p), path.dirname(p), path.basename(p, ".js"));
console.log(path.parse("/home/ada/notes/todo.md"));
console.log(path.format({ dir: "/var/log", name: "app", ext: ".log" }));
console.log(path.join("src", "pkg", "..", "lib", "util.js"));
console.log(path.normalize("a//b/./c/../d/"));
console.log(path.resolve("/srv", "www", "index.html"));
console.log(path.resolve("/srv", "/etc", "passwd")); // a later absolute path wins
console.log(path.relative("/srv/www/img", "/srv/www/css/site.css"));
console.log(path.isAbsolute("./x"), path.isAbsolute("/x"));
console.log(path.win32.join("C:\\Users", "ada", "file.txt"), path.posix.sep, path.win32.sep);
// Never trust user input in paths: check the result stays inside the root
function safeJoin(root, userPath) {
const full = path.resolve(root, "." + path.sep + userPath);
if (full !== root && !full.startsWith(root + path.sep)) throw new Error("path escapes root");
return full;
}
console.log(safeJoin("/srv/public", "img/logo.png"));
try {
safeJoin("/srv/public", "../../etc/passwd");
} catch (err) {
console.log(err.message);
}
report.test.js .js src/pkg report.test
{
root: '/',
dir: '/home/ada/notes',
base: 'todo.md',
ext: '.md',
name: 'todo'
}
/var/log/app.log
src/lib/util.js
a/b/d/
/srv/www/index.html
/etc/passwd
../css/site.css
false true
C:\Users\ada\file.txt / \
/srv/public/img/logo.png
path escapes root
basename,extname,dirnameandparsesplit a path apart;formatputs one together.joinconcatenates segments and normalizes the result.normalizecleans up..,.and doubled separators.resolveproduces an absolute path, working from right to left until it has one, and falling back to the current directory. A later absolute argument replaces everything before it.relative(from, to)gives the path from one location to another.path.posixandpath.win32give each platform's behavior on any platform.
These are pure string operations: they never check the file system. fs.realpath() asks the file system to resolve symbolic links to the real, canonical path.
Never trust paths from users
A server that serves path.join(root, requestedPath) is vulnerable to path traversal: a request for ../../etc/passwd reads files outside the intended folder. Resolve the path and check that the result is still inside the root, as safeJoin does. Note the root + path.sep check: a plain startsWith(root) would also accept /srv/public-secrets.
Reading files

const fs = require("node:fs");
const fsp = require("node:fs/promises");
const os = require("node:os");
const path = require("node:path");
const readline = require("node:readline");
async function main() {
const dir = await fsp.mkdtemp(path.join(os.tmpdir(), "read-"));
const csv = path.join(dir, "scores.csv");
await fsp.writeFile(csv, "name,score\nAda,91\nLin,78\nSam,85\n");
// 1. Whole file at once: a Buffer, or a string with an encoding
const bytes = await fsp.readFile(csv);
const text = await fsp.readFile(csv, "utf8");
console.log(bytes.length, "bytes;", text.split("\n")[1]);
// 2. Line by line through a stream: memory stays small for huge files
const lines = readline.createInterface({ input: fs.createReadStream(csv), crlfDelay: Infinity });
let total = 0, count = 0;
for await (const line of lines) {
if (count++ === 0) continue; // skip the header
total += Number(line.split(",")[1]);
}
console.log("average:", total / (count - 1));
// 3. A byte range: open a FileHandle and read at a position
const handle = await fsp.open(csv, "r");
try {
const buf = Buffer.alloc(3);
const { bytesRead } = await handle.read(buf, 0, 3, 11); // 3 bytes at offset 11
console.log(bytesRead, JSON.stringify(buf.toString()));
} finally {
await handle.close(); // always close what you open
}
// A missing file rejects with an ENOENT error
try {
await fsp.readFile(path.join(dir, "nope.csv"), "utf8");
} catch (err) {
console.log(err.code, err.syscall);
}
await fsp.rm(dir, { recursive: true });
}
main();
32 bytes; Ada,91
average: 84.66666666666667
3 "Ada"
ENOENT open
- Whole file:
readFile(path)returns a Buffer;readFile(path, "utf8")returns a string. This is the simplest choice for anything that comfortably fits in memory. - Streaming:
fs.createReadStream(path, options)returns a readable stream (article 126).optionscan includeencoding,startandendbyte positions, andhighWaterMark.readline.createInterfaceturns a stream into lines forfor await;crlfDelay: Infinitytreats\r\nas a single line break. - Random access:
fsp.open(path, "r")returns aFileHandle.handle.read(buffer, offset, length, position)readslengthbytes from filepositionintobufferatoffset, and resolves to{ bytesRead, buffer }, wherebytesReadcan be smaller near the end of the file. This suits binary formats whose header says where the data lives (article 124).
Every opened handle must be closed: a process can only have a limited number of open files, and leaked handles eventually cause EMFILE errors. Use try/finally as shown, or await using handle = await fsp.open(path) (article 100), which closes it automatically at the end of the block.
Failures reject with an Error carrying code (ENOENT for a missing file, EACCES for no permission, EISDIR when the path is a directory), plus syscall and path.
Common questions
Why does my script find data.json when run from one folder but not another?
Relative paths are resolved against the current working directory, not the script's location. Use path.join(__dirname, "data.json") or import.meta.dirname.
Should I check fs.existsSync before reading a file?
Usually not. The file can be deleted between the check and the read, so you'd need the error handling anyway. Just read it and handle ENOENT.
Is path.join or path.resolve right for building a file path?
join keeps relative paths relative; resolve always returns an absolute path. Use resolve when you need an absolute result, and remember that an absolute later argument resets it.
Summary
processreports the version, platform, memory, CPU time and working directory;node:osreports CPUs, memory, directories and network interfaces.fsoperations come as callback, Sync and promise variants, plus file descriptor (f...) and symbolic link (l...) versions. Usenode:fs/promisesin application code.- Use
node:path(join,resolve,relative,parse, ...) instead of string concatenation, build paths from__dirnameorimport.meta.dirname, and confine user-supplied paths to a root folder. - Read whole files with
readFile, large files with streams andreadline, and byte ranges with aFileHandle, closing it afterwards.
Practice Questions
What does path.resolve("/data", "logs", "../app.log") return on Linux?
Answer
"/data/app.log". The segments are joined to /data/logs/../app.log, and the .. removes logs.
Why is fs.readFileSync fine in a build script but a problem inside an HTTP request handler?
Answer
It blocks the event loop until the read finishes. A one-off script has nothing else to do, but a server can't handle any other request during that time. Use await readFile in request handlers.
Write an async function firstBytes(file, n) that returns the first n bytes of a file as a Buffer without reading the whole file.
Answer
const fsp = require("node:fs/promises");
async function firstBytes(file, n) {
const handle = await fsp.open(file, "r");
try {
const buf = Buffer.alloc(n);
const { bytesRead } = await handle.read(buf, 0, n, 0);
return buf.subarray(0, bytesRead); // the file may be shorter than n
} finally {
await handle.close();
}
}
A static file server uses path.join(publicDir, req.url). What attack does that allow?
Answer
Path traversal: a URL like /../../etc/passwd produces a path outside publicDir. Resolve the path and verify that it still starts with publicDir + path.sep before reading.
Previous: Writing Streams: Backpressure, Flowing and Paused Modes, Custom Streams and Web Streams
Next: Writing Files, File Operations, Metadata and Directories in Node

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.