TExcelTAD
Home › Node.js › Node.js Path Module

Node.js Path Module

Almost every Node.js program that touches files has to build a file path somewhere. Gluing strings together with "/" looks easy, but it breaks quickly: Windows uses \ as a separator, users type paths with trailing slashes, and relative segments like .. need to be resolved. The built-in node:path module does all of that for you, correctly, on every operating system.

node
import path from 'node:path';          // ES module
const path = require('node:path');     // CommonJS

Platform-aware vs. POSIX paths

path follows the conventions of the operating system the program runs on. If you need predictable results everywhere (for URLs, archives or tests), use the explicit variants:

Object Separator Use it for
path depends on the OS real files on the current machine
path.posix / URLs, Linux/macOS paths, consistent output
path.win32 \ Windows paths, even when running on Linux

The examples below use path.posix so that the output is the same on every computer.

Taking a path apart

node · try it yourself
const path = require('node:path').posix;

const file = '/home/ana/projects/shop/src/index.test.js';

console.log(path.dirname(file));
console.log(path.basename(file));
console.log(path.basename(file, '.js'));
console.log(path.extname(file));
console.log(path.parse(file));
/home/ana/projects/shop/src
index.test.js
index.test
.js
{
  root: '/',
  dir: '/home/ana/projects/shop/src',
  base: 'index.test.js',
  ext: '.js',
  name: 'index.test'
}

Notice that extname() only returns the last extension, .js, not .test.js. path.format() is the reverse of path.parse(): it builds a path string from such an object.

Joining and resolving

path.join() glues segments together with the correct separator and normalizes the result — duplicate slashes disappear and ./.. segments are resolved. path.resolve() goes further: it processes the segments from right to left until it has an absolute path, using the current working directory if needed.

node · try it yourself
const path = require('node:path').posix;

console.log(path.join('src', 'utils', '..', 'models', 'user.js'));
console.log(path.join('/var/', '/log//', 'app.log'));
console.log(path.normalize('./docs/../docs/./guide.md'));

console.log(path.resolve('/srv/app', 'public', 'img'));
console.log(path.resolve('/srv/app', '/etc', 'hosts'));

console.log(path.relative('/srv/app/src', '/srv/app/public/index.html'));
console.log(path.isAbsolute('/srv/app'), path.isAbsolute('srv/app'));
src/models/user.js
/var/log/app.log
docs/guide.md
/srv/app/public/img
/etc/hosts
../public/index.html
true false

In the second resolve() call, /etc is already absolute, so everything to its left is discarded.

Tip: Use path.join() when you want a relative path and path.resolve() when you need an absolute one — for example before passing a path to another process.

Windows paths

Even on Linux you can work with Windows paths through path.win32:

node · try it yourself
const { win32 } = require('node:path');

const p = win32.join('C:\\Users\\ana', 'Documents', '..', 'report.xlsx');
console.log(p);
console.log(win32.basename(p));
console.log(win32.sep, win32.delimiter);
console.log(require('node:path').posix.sep, require('node:path').posix.delimiter);
C:\Users\ana\report.xlsx
report.xlsx
\ ;
/ :

sep is the separator between folders; delimiter is the separator used in lists of paths such as the PATH environment variable.

Paths relative to the current file

A relative path like 'data.json' is resolved against the current working directory — the folder you ran node from — not the folder that contains your script. To read a file that sits next to your code, build the path from the script's own location:

Module type Folder of the current file
CommonJS __dirname
ES module (Node 20.11+) import.meta.dirname
ES module (older) path.dirname(fileURLToPath(import.meta.url))
node
// config.mjs
import path from 'node:path';
import { readFile } from 'node:fs/promises';

const configPath = path.join(import.meta.dirname, 'config.json');
const config = JSON.parse(await readFile(configPath, 'utf8'));
node · try it yourself
import path from 'node:path';

// import.meta.filename is the absolute path of this file
console.log(path.basename(import.meta.filename));
console.log(import.meta.dirname === path.dirname(import.meta.filename));
main.mjs
true

Note: The file is called main.mjs because that is how the example is saved when it runs. On your own computer you would see your file's name.

Common functions

Function Returns
join(...parts) joined and normalized path
resolve(...parts) absolute path
normalize(p) cleaned-up path
relative(from, to) path from from to to
dirname(p) / basename(p, ext?) / extname(p) parts of a path
parse(p) / format(obj) path ↔ object
isAbsolute(p) true if p starts at the root
sep / delimiter / and : on POSIX, \ and ; on Windows

Test yourself

What does path.posix.extname('archive.tar.gz') return?

  1. .tar.gz
  2. .gz
  3. gz
  4. archive

What does path.posix.resolve('/a', '/b', 'c') return?

  1. /a/b/c
  2. /b/c
  3. a/b/c
  4. /a/c

In an ES module, which expression gives the folder that contains the current file?

  1. __dirname
  2. process.cwd()
  3. import.meta.dirname
  4. path.dirname('.')