Node.js Introduction
Overview
Historically, JavaScript was trapped inside the web browser, only capable of manipulating the DOM or showing alerts. In 2009, Ryan Dahl ripped the V8 JavaScript Engine out of Google Chrome, bolted it to a C++ library, and called it Node.js. Node.js is NOT a framework or a language; it is a Runtime Environment. It allows JavaScript to run directly on the Operating System (servers), giving it the power to read files, connect to databases, and handle network traffic, making JS a full-stack language.
Syntax
// 1. You no longer have access to Browser APIs!
// console.log(window); // FATAL ERROR: window is not defined
// console.log(document); // FATAL ERROR: document is not defined
// 2. You DO have access to OS-level APIs!
const os = require('os');
console.log(os.platform()); // 'darwin' (macOS), 'win32' (Windows), 'linux'
console.log(os.cpus().length); // Prints how many CPU cores your server has!
// 3. Executing a Node script from the terminal:
// $ node server.jsCommon Pitfalls
- Assuming Node.js is a 'Backend Framework'. Node.js is just the engine (like the JVM for Java or the Python Interpreter). Express.js or NestJS are the actual frameworks built on top of Node.js.
- Trying to use
alert()orlocalStoragein a Node script. Because there is no Chrome browser rendering a GUI, these global browser objects literally do not exist in the Node runtime.
Interview Questions
Node.js is 'Single-Threaded' when executing your JavaScript code. However, under the hood, the C++ libraries it relies on (like libuv) manage a hidden multi-threaded Thread Pool (usually 4 threads) to offload heavy OS tasks like File I/O and Cryptography, preventing the main JS thread from blocking.
Real-World Example
Writing a simple server that returns 'Hello World' using raw Node.js.
// This is built directly into Node! No npm installs needed.
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello from the Node Runtime!');
});
server.listen(3000, () => console.log('Server is alive!'));Check Your Knowledge
Test your understanding of Node.js Introduction with these quick questions.