Initializing Core...
Initializing Core...
Operational
Node.js comes with built-in modules (no need to install them with npm). Some important ones are:
const fs = require('fs');// Reading a filefs.readFile('example.txt', 'utf8', (err, data) => {if (err) {console.error("Error reading file:", err);return;}console.log("File Content:", data);});
With Node.js, you don’t need Apache or Nginx — you can create your own server!
const http = require('http');// Create a serverconst server = http.createServer((req, res) => {res.writeHead(200, { 'Content-Type': 'text/plain' });res.end('Hello, World! 🌎');});// Listen on port 3000server.listen(3000, () => {console.log('Server is running at http://localhost:3000');});
node server.jsOpen your browser → http://localhost:3000 🎉
We can handle different pages (routes) based on the URL:
const http = require('http');const server = http.createServer((req, res) => {if (req.url === "/") {res.writeHead(200, { 'Content-Type': 'text/plain' });res.end('Welcome to Home Page 🏠');} else if (req.url === "/about") {res.writeHead(200, { 'Content-Type': 'text/plain' });res.end('About Us Page ℹ️');} else {res.writeHead(404, { 'Content-Type': 'text/plain' });res.end('Page Not Found ❌');}});server.listen(3000, () => {console.log('Server running at http://localhost:3000');});
Instead of plain text, let’s serve an HTML page:
const http = require('http');const fs = require('fs');const server = http.createServer((req, res) => {if (req.url === "/") {fs.readFile('index.html', (err, data) => {if (err) {res.writeHead(500);res.end('Error loading page');} else {res.writeHead(200, { 'Content-Type': 'text/html' });res.end(data);}});}});server.listen(3000, () => {console.log('Server is running at http://localhost:3000');});
👉 Create a file index.html in the same folder:
<!DOCTYPE html><html><head><title>My Node Server</title></head><body><h1>Welcome to Node.js Server 🎉</h1></body></html>