Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 133 ยท The Runtime

The os and path Modules

Learn the Node.js path module (join, resolve, relative, parse, posix vs win32, traversal safety), the os module basics and how to convert between file paths and file URLs.

Programs constantly handle file locations: where a config file lives, where to write a report, which asset a request asks for. A path looks like plain text, so beginners build it with string concatenation, and then discover that Windows uses backslashes, that a doubled slash is a bug, and that ../ in user input can escape a folder. The node:path module exists so you never concatenate paths by hand. Its companion, node:os, tells you facts about the machine your program runs on, such as the line ending or the temp folder.

Both modules are pure helpers. path never touches the disk: it only manipulates strings according to the rules of an operating system. That makes it fast, predictable and very easy to test. In this lesson you will learn the functions you will use every day, the difference between the POSIX and Windows flavours, how to handle paths safely, how to convert paths to file: URLs, and which os values are safe to rely on. File reading and writing itself comes later, in Reading and Writing Files.

Why not concatenate strings?

Look at what goes wrong with a naive approach:

Node.js String concatenation versus path.join

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Concatenation produced /data/uploads///report.pdf (three slashes in a row), which often still works but is wrong and breaks comparisons. path.join normalises: it removes the duplicated separator and uses the right separator for the platform. Notice that we used path.posix and path.win32 explicitly to show both rules on one machine; we explain that next.

POSIX versus Windows

Operating systems disagree on paths. Linux and macOS use / as the separator and have a single root, /. Windows uses \ (and also accepts /), has drive letters such as C:\, and may use UNC names such as \\server\share. The module exports the implementation for the platform you run on as path itself, and both implementations always as path.posix and path.win32.

Node.js The two flavours side by side

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Our server runs Linux, so path equals path.posix here; on a Windows laptop the same first lines would show "\\" and ";" and false. The last two lines are a classic bug: parsing a Windows path with the POSIX rules treats the backslashes as ordinary characters, so the whole string becomes the file name. When your program handles paths from another system (for example log lines or archive entries), pick the matching flavour explicitly. In everyday code that works with the local file system, use plain path.

path.delimiter is the separator inside lists such as the PATH environment variable (: on POSIX, ; on Windows).

The everyday functions

join and normalize

path.join(...parts) glues the parts with the platform separator and then normalises the result: it collapses repeated separators and resolves . and .. segments. An empty result becomes .. path.normalize(p) does only the cleaning for a single string.

Node.js join and normalize

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The last line is a preview of a security problem: joining a fixed base with a user-controlled part can climb out of the base. Here /base plus ../../etc/passwd became /etc/passwd, because .. cannot go above the root / and simply stops there. We return to that in the safety section.

resolve: building an absolute path

path.resolve(...parts) works like repeated cd commands: it processes the parts from right to left until it has built an absolute path; if the parts alone are not enough, it prepends the current working directory. An absolute part discards everything to its left.

Node.js resolve works like cd

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Two things catch people out. First, an absolute second argument replaces the first, as the /etc line shows; this is a frequent source of "path traversal" bugs when the second argument comes from a user. Second, resolve('x') depends on the current working directory (process.cwd()), which is where the process was started, not where your source file lives. When you want a path relative to the file, build it from import.meta.dirname (in ESM) or __dirname (in CommonJS):

NODE
import path from 'node:path';

const configPath = path.join(import.meta.dirname, 'config', 'default.json');

import.meta.dirname and import.meta.filename are available in ES modules since Node 20.11/21.2. In older code you will see path.dirname(fileURLToPath(import.meta.url)), which we explain below.

relative

path.relative(from, to) answers "how do I get from this directory to that one?". Both arguments are resolved first, and the result is the shortest relative path.

Node.js relative paths

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

If the two paths are the same, the result is an empty string. A result that starts with .. means the target is outside the starting directory, a fact that is very useful for safety checks.

basename, dirname, extname

These three take a path apart. basename is the last segment, dirname is everything before it, and extname is the extension, from the last dot to the end.

Node.js basename, dirname and extname

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Pitfalls worth knowing:

  • extname('archive.tar.gz') is only .gz; compound extensions need your own logic.
  • A file that begins with a dot, like .bashrc, has an empty extension, because the dot is part of the name.
  • A trailing separator is ignored by basename, so /var/log/ gives log.

parse and format

path.parse(p) returns an object with root, dir, base, ext and name. path.format(obj) does the reverse. Together they make renaming easy without regular expressions.

Node.js Changing an extension with parse and format

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

format prefers base over name plus ext, which is a subtle rule: if you copy a parsed object and change only name, nothing happens because the old base still wins. Delete base or build a new object as above.

isAbsolute

path.isAbsolute(p) tells you whether a path is complete without needing a working directory. On POSIX it means "starts with /". On Windows it is subtler: C:\x is absolute, but C:x (a drive-relative path) is not.

Paths from users: staying safe

Whenever part of a path comes from outside (a URL, an upload file name, a form), assume it is hostile. The classic attack is path traversal: a request for ../../etc/passwd that makes your server read files outside the public folder.

Node.js A path traversal bug and its fix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the table. The naive version happily returns /srv/etc/passwd for the second attempt and /srv/site/secret.txt for the fourth, both outside the public folder. The safe version resolves the final path first and then asks relative(root, full) whether the target is below the root: a result starting with .. means it escaped (it returns null), and an empty result means it is the root itself. The absolute attempt /etc/passwd is not an escape at all here, because we force every input to be relative with a leading ./, so it simply names a file called etc/passwd inside the public folder. A related defence is to reject any input that contains a NUL character or that the operating system would treat as a different path after decoding, so decode URLs before checking.

String checks such as userPath.includes('..') are not enough: encoded forms, symbolic links and Windows alternatives (..\) bypass them. Always resolve to a final path and compare it to the allowed root. For symbolic links you must also resolve the real path with fs.realpath, covered in Paths, Permissions and Safe File Handling.

Paths and file URLs

ES modules identify themselves with a URL, import.meta.url, for example file:///srv/app/main.mjs. A file URL is not a path: spaces become %20, and Windows adds a leading slash and a drive. Two helpers in node:url convert between them.

Node.js fileURLToPath and pathToFileURL

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Never convert a file URL by hand with url.pathname: it keeps %20 encoded and, on Windows, returns /C:/Users/.... fileURLToPath handles all of that and throws for non-file URLs. The URL class itself is the topic of URLs, URLSearchParams and URLPattern.

The os module

node:os reports facts about the operating system. Treat most of them as inputs for decisions rather than output to print, since values differ from machine to machine.

Node.js Portable os values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

What each is good for:

  • os.EOL is rarely needed. Files you write for other programs are usually fine with \n, which almost every tool reads on any platform. Use EOL when a Windows-only tool is the consumer.
  • os.tmpdir() and os.homedir() return absolute directories. Combine them with path.join, and prefer fs.mkdtemp for unique temporary folders.
  • os.availableParallelism() is the right number for sizing a worker pool, better than os.cpus().length because it respects container limits. We use it in Worker Threads.
  • os.constants.signals maps names such as SIGTERM to numbers; errno does the same for error codes like ENOENT.
  • os.hostname(), os.totalmem(), os.freemem(), os.cpus(), os.networkInterfaces() and os.userInfo() exist too. They return different values on every machine and every call, so never put them in tests or in output you compare.

For one more piece of machine information, see the process object in The process Object.

A small toolbox: putting it together

Node.js Organising files by extension

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice that no string splitting, no regular expressions and no hard-coded slashes appear. That is the point of the module: describe what you want with parse, join and relative, and let it handle the details.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does path.resolve('/a/b', '/x', 'y') return on Linux?

    resolve processes the parts from right to left and stops as soon as it has an absolute path. The absolute part /x discards /a/b.
  2. 2. Which statement about path.extname('.bashrc') is correct?

    A leading dot belongs to the file name, not to an extension, so extname returns an empty string.
  3. 3. Why is path.posix.join(root, userInput) alone unsafe for serving files?

    join normalises .. segments, so root plus ../../etc/passwd ends up outside the root. Resolve the final path and check it is still inside the root.
  4. 4. What is the best way to get the directory of the current ES module file in modern Node.js?

    import.meta.dirname gives the module's directory directly. process.cwd() is the process working directory, __dirname does not exist in ES modules, and pathname leaves percent-encoding in place.
  5. 5. Which value of path.relative(root, target) tells you target is outside root?

    A relative path that begins with .. needs to go up from root, so the target is outside it. An empty string means the two paths are the same.

Summary

  • Never build paths by string concatenation; use path.join, path.resolve and friends.
  • join glues and normalises, resolve builds an absolute path from right to left, relative finds the way between two paths.
  • basename, dirname, extname, parse and format take paths apart and put them together.
  • path.posix and path.win32 are always available; plain path is the one for the current platform.
  • For user-supplied paths, resolve the final path and verify it stays inside the allowed root.
  • Use fileURLToPath and pathToFileURL to convert between file: URLs and paths; import.meta.dirname is the easy way to find files next to your module.
  • os provides EOL, tmpdir, homedir, parallelism and constants; avoid printing machine-specific values.

Next: URLs, URLSearchParams and URLPattern