Topic 6 of 37
Running Code with Node.js
Overview
Node.js allows you to run JavaScript outside the browser. It uses the V8 engine but replaces browser APIs (like DOM/window) with system APIs (like file system access, HTTP servers). This enables JS to be a full-stack language.
Syntax
You execute files using the 'node' command. You have access to built-in modules like 'os', 'fs', and 'http'.
Executing a JS File
javascript
// In your terminal:
// node script.js
// Inside script.js:
const os = require('os');
console.log("Free memory: ", os.freemem());Common Pitfalls
- Trying to use 'window' or 'document' inside Node.js—it will throw a ReferenceError because the DOM doesn't exist on servers.
Interview Tips
- Understand the difference between the Node.js environment (has 'global', 'process', file system) and the Browser environment (has 'window', 'document', DOM).
Real-World Example
Building a quick web server.
example
javascript
const http = require('http');
const server = http.createServer((req, res) => {
res.end("Hello from Node.js Server!");
});
server.listen(3000, () => console.log("Server running"));