Node.js lets you run JavaScript outside the browser, so you can build fast and scalable servers using one language.
0
0
Why Node.js for server-side JavaScript in Node.js
Introduction
You want to build a web server that handles many users at the same time.
You want to use JavaScript for both frontend and backend to keep things simple.
You need a fast way to handle real-time data like chat or live updates.
You want to build APIs that connect your app to databases or other services.
You want to create tools or scripts that run on your computer using JavaScript.
Syntax
Node.js
import http from 'node:http'; const server = http.createServer((req, res) => { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello from Node.js!'); }); server.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Node.js uses modules to organize code, like 'http' for creating servers.
You write JavaScript code that runs on your computer, not in a browser.
Examples
Reading a file asynchronously using Node.js built-in 'fs' module.
Node.js
import fs from 'node:fs'; fs.readFile('file.txt', 'utf8', (err, data) => { if (err) throw err; console.log(data); });
Reading a file synchronously, blocking code until done.
Node.js
import { readFileSync } from 'node:fs'; const data = readFileSync('file.txt', 'utf8'); console.log(data);
Using Express framework on Node.js to create a simple web server.
Node.js
import express from 'express'; const app = express(); app.get('/', (req, res) => { res.send('Hello from Express on Node.js!'); }); app.listen(3000);
Sample Program
This program creates a simple web server using Node.js. When you visit the homepage, it shows a welcome message. For other pages, it shows a 404 message.
Node.js
import http from 'node:http'; const server = http.createServer((req, res) => { if (req.url === '/') { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Welcome to Node.js server!'); } else { res.writeHead(404, {'Content-Type': 'text/plain'}); res.end('Page not found'); } }); server.listen(3000, () => { console.log('Server running at http://localhost:3000'); });
OutputSuccess
Important Notes
Node.js uses an event-driven, non-blocking model to handle many tasks at once efficiently.
It is great for apps that need to handle many connections without slowing down.
Node.js has a large community and many ready-to-use packages to speed up development.
Summary
Node.js lets you use JavaScript on the server to build fast and scalable apps.
It works well for real-time apps and when you want one language for frontend and backend.
Node.js uses modules and an event-driven model to handle many tasks efficiently.