Introduction to Node.js
Server-side JavaScript — the event loop, V8, and your first Node program
Skills taught: node.runtime, node.event-loop, node.globals, node.process
Node.js global objects
// Node.js global objects — available in every .js file
// process: info about the current Node process
console.log('Node version:', process.version); // e.g. 'v20.11.0'
console.log('Platform:', process.platform); // 'linux', 'win32', 'darwin'
console.log('Working dir:', process.cwd()); // current directory
console.log('Script args:', process.argv); // ['node', 'script.js', ...extra]
// __dirname and __filename (CommonJS only)
console.log('Dir:', __dirname); // absolute path of current directory
console.log('File:', __filename); // absolute path of current file
// Environment variables
console.log('PORT:', process.env.PORT || 3000);
console.log('NODE_ENV:', process.env.NODE_ENV || 'development');
// Exit the process
// process.exit(0); // 0 = success, non-zero = error
// The event loop — non-blocking async execution
console.log('1: start'); // runs immediately (sync)
setTimeout(() => {
console.log('3: setTimeout (0ms)'); // runs after sync code + nextTick
}, 0);
Promise.resolve().then(() => {
console.log('2b: Promise microtask'); // microtask queue (before next tick)
});
process.nextTick(() => {
console.log('2a: nextTick'); // runs before Promises, before setTimeout
});
console.log('2: end'); // runs immediately (sync)
// Output order: 1, 2, 2a, 2b, 3
// sync code → nextTick → Promise microtasks → setTimeout
Tip: This sandbox simulates Node.js in-browser. `require('path')`, `require('fs')`, `require('os')`, `require('events')`, `process`, `__dirname`, and `__filename` all work. npm packages and actual server-starting require a real Node.js install.
Frequently Asked Questions
Should I use CommonJS (require) or ES Modules (import)?
New projects should use ES Modules (import/export) — they're the standard. Set `"type": "module"` in package.json. CommonJS (require/module.exports) is older but still dominates the npm ecosystem. Many tutorials use CommonJS. Both work in Node.js 20; you can convert with the .mjs extension or the type field. Node's built-in modules work with both: `import { readFile } from 'node:fs/promises'` or `const { readFile } = require('fs/promises')`.