NelsonLabs
Node.js Fundamentals/Path & OS Modules

Path & OS Modules

The path and os modules are workhorses you'll use constantly β€” path for safely building file paths, os for system information.

The path module
javascript
const path = require("path");

// __dirname β€” absolute path to the current file's directory
// __filename β€” absolute path to the current file
console.log(__dirname);   // /Users/nelson/projects/myapp/src
console.log(__filename);  // /Users/nelson/projects/myapp/src/index.js

// path.join β€” builds paths correctly for the OS
const configPath = path.join(__dirname, "config", "db.json");
// Unix: /Users/nelson/projects/myapp/src/config/db.json
// Windows: C:Users
elsonprojectsmyappsrcconfigdb.json

// path.resolve β€” absolute path from relative
path.resolve("src", "index.js");  // /cwd/src/index.js

// path.parse β€” break apart a path
path.parse("/home/nelson/logs/server.log");
// { root: '/', dir: '/home/nelson/logs', base: 'server.log',
//   ext: '.log', name: 'server' }

// Get just the parts you need
path.basename("/src/utils/helper.js");  // "helper.js"
path.dirname("/src/utils/helper.js");   // "/src/utils"
path.extname("index.html");             // ".html"
The os module
javascript
const os = require("os");

os.platform()    // "linux", "darwin" (Mac), "win32"
os.arch()        // "x64", "arm64"
os.cpus()        // array of CPU core info
os.totalmem()    // total RAM in bytes
os.freemem()     // available RAM in bytes
os.homedir()     // "/Users/nelson" or "C:\Users\Nelson"
os.tmpdir()      // temp directory
os.hostname()    // machine name

// Useful for displaying readable memory:
const totalGB = (os.totalmem() / 1024 ** 3).toFixed(1);
const freeGB  = (os.freemem()  / 1024 ** 3).toFixed(1);
console.log(`Memory: ${freeGB}GB free of ${totalGB}GB`);