01 - What is Node.js
📋 Jump to TakeawaysJavaScript Outside the Browser
Node.js runs JavaScript on your machine instead of in a browser. It uses V8, the same engine Chrome uses, but strips out browser APIs (no document, no window) and adds system-level ones instead (file access, networking, processes).
// This works in Node, not in a browser
const os = require('os');
console.log(os.platform()); // "darwin" (macOS), "linux", or "win32"
console.log(os.cpus().length); // 10 (number of CPU cores)Running a File
Create a file and run it. That's it.
// hello.js
console.log('Running in Node.js', process.version);
// Running in Node.js v20.11.0node hello.jsNo HTML file. No script tag. No browser. Just node filename.js.
The Event Loop
Node.js is single-threaded but non-blocking. It doesn't wait for slow operations (reading files, network requests). It starts the operation, moves on, and comes back when it's done.
const fs = require('fs');
console.log('1: before read');
fs.readFile('hello.js', 'utf-8', (err, data) => {
console.log('3: file read done');
});
console.log('2: after read');
// Output:
// 1: before read
// 2: after read
// 3: file read doneThe file read doesn't block. Line 2 runs before line 3 because readFile is asynchronous. This is how Node handles thousands of connections with a single thread.
Global Objects
Node.js has its own globals instead of browser ones.
| Browser | Node.js | Purpose |
|---|---|---|
window |
global / globalThis |
Global scope |
document |
— | DOM (doesn't exist in Node) |
| — | process |
Current process info |
| — | __dirname |
Directory of current file |
| — | __filename |
Full path of current file |
| — | Buffer |
Binary data handling |
console.log(__dirname); // /Users/you/projects/my-app
console.log(__filename); // /Users/you/projects/my-app/hello.js
console.log(process.pid); // 12345 (process ID)Node REPL
Type node with no arguments to get an interactive shell.
$ node
> 2 + 2
4
> 'hello'.toUpperCase()
'HELLO'
> .exitUseful for quick experiments. Press Ctrl+C twice or type .exit to quit.
Key Takeaways
- Node.js runs JavaScript outside the browser using the V8 engine
- Run files with
node filename.js, no browser needed - Single-threaded but non-blocking: async operations don't freeze execution
- No
windowordocument, instead you getprocess,__dirname,Buffer nodewith no arguments opens an interactive REPL- The event loop is why Node can handle many connections on one thread