Node.js Path Module
A filesystem path is not a URL and is not automatically relative to the source file. Choose its base before joining names or deciding which location is allowed.
How it works
path functions perform platform-aware string operations. A lexical containment check can reject an obvious parent-directory escape, but it does not stop symlink races or provide an operating-system sandbox. Keep filenames application-controlled where possible. This example uses a fixed virtual base and accepts one simple child name; it never opens that path. File-reading lessons then demonstrate actual operations in owned temporary folders.
Run the code
Run this example locally with Node.js. The exact sources are reviewed on Node 22.15.1 and Node 24.22.1 unless a specialised lab states otherwise. Save the complete source as paths.mjs in a separate empty exercises folder and run node paths.mjs. There is no Node.js browser runner on Bhylu; the plain JavaScript playground does not provide these filesystem, server or process APIs.
Download the complete source. Ordinary Node scripts need no Apache, PHP or MySQL service. File examples own their temporary folders; network fixtures use loopback and available temporary ports.
Example
import path from 'node:path';
function childPath(base, name) {
const root = path.resolve(base);
const target = path.resolve(root, name);
const relative = path.relative(root, target);
if (
!relative ||
relative.startsWith('..' + path.sep) ||
relative === '..' ||
path.isAbsolute(relative)
)
throw new Error('Outside base');
return target;
}
console.log(path.basename(childPath('desk-reports', 'summary.json')));
try {
childPath('desk-reports', '../private.txt');
} catch (error) {
console.log(error.message);
}
Expected result
summary.json Outside base
The ordinary report name stays inside the lexical base and the traversal attempt is rejected. This is one component of a file policy, not permission to serve arbitrary requested paths from a web endpoint.
Use the Node.js API reference for the precise version contract.