Node.js lets you run JavaScript outside the browser. It helps build fast and scalable apps on your computer or server.
0
0
What is Node.js in Node.js
Introduction
When you want to build a web server to handle many users at once.
When you need to create tools that run on your computer using JavaScript.
When you want to build real-time apps like chat or games.
When you want to handle files or databases on a server with JavaScript.
When you want to run JavaScript code without opening a browser.
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 at http://localhost:3000/'); });
This example shows how to create a simple web server in Node.js.
Node.js uses modules like 'http' to add features beyond JavaScript's basics.
Examples
Prints a message to the console using Node.js.
Node.js
console.log('Hello, Node.js!');Reads a file asynchronously and prints its content.
Node.js
import fs from 'node:fs'; fs.readFile('file.txt', 'utf8', (err, data) => { if (err) throw err; console.log(data); });
Shows how to get system information using Node.js built-in modules.
Node.js
import os from 'node:os'; console.log('Your system platform is:', os.platform());
Sample Program
This program creates a simple web server that listens on port 3000. When you open http://localhost:3000/ in your browser, it shows the message 'Hello from Node.js!'.
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 at http://localhost:3000/'); });
OutputSuccess
Important Notes
Node.js uses an event-driven, non-blocking model to handle many tasks efficiently.
It is great for building servers and tools using JavaScript outside the browser.
Summary
Node.js runs JavaScript on your computer or server, not just in browsers.
It helps build fast, scalable apps like web servers and real-time tools.
Node.js uses modules to add many useful features beyond basic JavaScript.