Node.js Basics & Runtime

Difficulty: Beginner

Question

What is Node.js and how does it differ from browser JavaScript? Explain the key global objects available in Node.js.

Answer

Node.js is a JavaScript runtime built on Chrome's V8 engine that allows JavaScript to run outside the browser. It provides access to the file system, network, OS, and other system-level APIs that browsers restrict for security.

Unlike browser JS, Node.js has no window or document objects. Instead it provides global objects like process (current process info, env vars, stdin/stdout), __dirname and __filename (current file paths), Buffer (binary data), and module/require (module system).

The process object is especially important. It gives access to environment variables via process.env, command line arguments via process.argv, and methods like process.exit() and process.cwd(). It also emits events like 'uncaughtException' and 'unhandledRejection' for error handling.

Node.js uses an event-driven, non-blocking I/O model which makes it efficient for I/O-heavy workloads like web servers, APIs, and real-time applications. However, it is not ideal for CPU-intensive tasks without worker threads.

Code examples

Key Global Objects in Node.js

// process object - info about current Node process
console.log('Node version:', process.version);
console.log('Platform:', process.platform);
console.log('PID:', process.pid);
console.log('CWD:', process.cwd());
console.log('Memory:', process.memoryUsage());

// Environment variables
console.log('NODE_ENV:', process.env.NODE_ENV);

// Command line arguments
// node app.js --port 3000
console.log('Args:', process.argv);
// ['node', '/path/app.js', '--port', '3000']

// __dirname and __filename (CommonJS only)
console.log('Directory:', __dirname);
console.log('File:', __filename);

These global objects give Node.js programs access to system information that browser JavaScript cannot reach.

Browser JS vs Node.js

// Browser-only APIs (NOT available in Node)
// window, document, localStorage, fetch (built-in since Node 18)
// alert(), confirm(), DOM manipulation

// Node-only APIs (NOT available in browser)
const fs = require('fs');       // File system
const path = require('path');   // Path utilities
const os = require('os');       // OS information
const http = require('http');   // HTTP server
const crypto = require('crypto'); // Cryptography

// Both environments
console.log('Works everywhere');
setTimeout(() => {}, 1000);
JSON.parse('{}');
Promise.resolve();

// globalThis works in both (ES2020+)
console.log(globalThis === global); // true in Node
// console.log(globalThis === window); // true in browser

Node.js provides system-level modules while browsers provide DOM and Web APIs. globalThis is the universal way to access the global object.

Process Event Handling

// Handle uncaught exceptions
process.on('uncaughtException', (err) => {
  console.error('Uncaught:', err.message);
  // Log, cleanup, then exit
  process.exit(1);
});

// Handle unhandled promise rejections
process.on('unhandledRejection', (reason, promise) => {
  console.error('Unhandled Rejection:', reason);
});

// Graceful shutdown on SIGTERM
process.on('SIGTERM', () => {
  console.log('SIGTERM received. Shutting down...');
  server.close(() => process.exit(0));
});

// Exit event
process.on('exit', (code) => {
  console.log('Process exiting with code:', code);
});

Process events let you handle crashes and signals gracefully. Always log uncaught exceptions and exit cleanly in production.

Key points

Concepts covered

V8 Engine, Runtime, Global Objects, process