agyanadda@gmail.com

Node.js path and os Modules

Node.js Core Modules 1 min read Updated Dec 3, 2026 Topic 7 of 30

The path module

Windows uses \ and Linux/macOS use / in paths. The path module builds correct paths on every system.

  • path.join('uploads', 'images', 'a.png') — joins parts with the right separator
  • path.resolve('data') — an absolute path
  • path.basename('/a/b/photo.jpg') → photo.jpg
  • path.extname('photo.jpg') → .jpg
  • path.dirname('/a/b/photo.jpg') → /a/b
  • path.parse(p) — all parts as an object

Combine with the file's folder to make paths that work wherever you run the command: path.join(import.meta.dirname, 'data.json').

The os module

  • os.platform(), os.type(), os.arch()
  • os.cpus().length — number of CPU cores
  • os.totalmem(), os.freemem() — bytes
  • os.homedir(), os.tmpdir(), os.hostname()
  • os.EOL — line ending for this system

Never build paths by joining strings with + '/' + — use path.join.

Example

Example — System report JavaScript
import path from 'node:path';
import os from 'node:os';

const file = path.join('uploads', 'photos', 'profile.JPG');
console.log(file);                              // uploads/photos/profile.JPG (\ on Windows)
console.log(path.extname(file).toLowerCase());  // .jpg
console.log(path.basename(file, '.JPG'));        // profile

const gb = (bytes) => (bytes / 1024 ** 3).toFixed(1) + ' GB';
console.log({
  platform: os.platform(),
  cpus: os.cpus().length,
  totalMemory: gb(os.totalmem()),
  freeMemory: gb(os.freemem()),
  home: os.homedir(),
});

Prints the joined path with the correct separator, the extension .jpg, the name profile, and an object such as { platform: 'win32', cpus: 8, totalMemory: '16.0 GB', ... }.

Test Yourself With Exercises

Exercise 1 Multiple Choice

What does path.extname('report.pdf') return?

Exercise 2 True / False

path.join uses the correct separator for the operating system.

Exercise 3 Fill in the Blank

Get the number of CPU cores with os.___().length

Frequently Asked Questions

path.join simply joins the parts. path.resolve works from right to left and always returns an absolute path, using the current working folder if needed.