Node.js Overview
Introduction
Node.js is a JavaScript runtime built on Chromeβs V8 engine. It allows developers to build scalable and high-performance applications using an event-driven, non-blocking I/O model.
Installing Node.js
To install Node.js, download it from Node.js Official Website or use a package manager:
# For macOSbrew install node
# For Ubuntusudo apt install nodejs npmCheck the installation:
node -vnpm -vCreating a Simple Node.js Application
Create a file app.js and write the following code:
const http = require('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 port 3000');});Run the application:
node app.jsVisit http://localhost:3000 in a browser.
Using npm (Node Package Manager)
npm is used to manage packages in Node.js projects. Initialize a new project:
npm init -yInstall a package (e.g., Express):
npm install expressCreating a Basic Express Server
Install Express:
npm install expressCreate server.js:
const express = require('express');const app = express();
app.get('/', (req, res) => { res.send('Hello from Express!');});
app.listen(3000, () => { console.log('Server is running on port 3000');});Run the server:
node server.jsMiddleware in Express
Middleware functions handle requests before reaching routes. Example:
app.use((req, res, next) => { console.log('Request received'); next();});Working with File System (fs module)
Node.js provides fs module to interact with files.
Example:
const fs = require('fs');fs.writeFileSync('test.txt', 'Hello, Node.js!');console.log('File created');Using Environment Variables
Use dotenv to manage environment variables.
Install it:
npm install dotenvCreate a .env file:
PORT=3000Load it in server.js:
require('dotenv').config();console.log(process.env.PORT);Conclusion
Node.js is a powerful runtime for building scalable server-side applications. By leveraging npm packages and frameworks like Express, developers can quickly build and deploy web services.
Happy coding! π