File paths look different on different operating systems — Windows uses backslashes (C:\Users\name), Mac and Linux use forward slashes (/home/name). The path module builds and reads paths in a way that works correctly regardless of which one Node happens to be running on.
Never build a path by joining strings with + — use path.join():
const path = require('path')
const filePath = path.join('data', 'users', 'list.json')
console.log(filePath) // 'data/users/list.json' on Mac/Linux, 'data\\users\\list.json' on Windowspath.join() automatically uses the right separator for whichever system the code is running on — code written this way behaves the same on every operating system.
const filePath = '/projects/site/photo.png'
path.basename(filePath) // 'photo.png'
path.extname(filePath) // '.png'
path.dirname(filePath) // '/projects/site'A relative path like 'data.json' is resolved against the current working directory — wherever the terminal happened to be when the script started, which isn't always where the script file itself lives. __dirname always points to the folder containing the current file, so combining it with path.join() gives a path that works no matter where the script is run from:
const configPath = path.join(__dirname, 'config.json')os reports information about the machine Node is running on:
const os = require('os')
console.log(os.platform()) // 'win32', 'darwin', 'linux'
console.log(os.cpus().length) // number of CPU cores
console.log(os.freemem()) // free memory, in bytesYou won't reach for os often in everyday app code — it's mostly useful in command-line tools and scripts that need to behave differently depending on the machine they're running on.