The Node.js Runtime ExplainedLesson 1.5
Node.js built-in globals and useful CLI flags
__dirname, __filename, global object, Buffer, console methods, --watch flag, --inspect flag, NODE_ENV, .env files
Globals You Get for Free
Node.js injects several globals into every module. Unlike browser globals, these are specific to the runtime environment.
console.log(__dirname); // absolute path to current directory
console.log(__filename); // absolute path to current file
// Use __dirname for reliable file paths:
const path = require('path');
const config = path.join(__dirname, 'config', 'app.json');In ESM, __dirname is not available. Use import.meta.url instead:
import { fileURLToPath } from 'url';
import { dirname } from 'path';
const __dirname = dirname(fileURLToPath(import.meta.url));Useful CLI Flags
--watch (Node 18+) restarts on file changes — no nodemon needed for basic dev work. --inspect opens the V8 debugger so Chrome DevTools can attach.
node --watch src/index.js
node --inspect src/index.jsEnvironment Variables
Load .env files natively from Node 20.6+ with --env-file:
node --env-file=.env src/index.jsAlways add .env to .gitignore. Never commit secrets.
