Runtimes (NodeJS)
Node.js is an open-source JavaScript runtime environment, built on Google's V8 Chrome engine, that allows you to run JavaScript code on the server-side. Unlike traditional JavaScript environments that run in browsers, Node.js enables the creation of server applications, command-line tools, and much more.
Key Features
1. Event-Driven Architecture
Node.js uses a non-blocking, event-driven I/O model, which makes it efficient and suitable for real-time applications that need to handle many simultaneous connections.
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
2. Single-Threaded with an Event Loop
Node.js operates on a single thread, using an event loop to manage asynchronous operations. This allows it to handle multiple concurrent connections without the overhead of creating new threads for each connection.
3. NPM (Node Package Manager)
NPM is the Node.js package manager, which facilitates code sharing and reuse. It is one of the largest software repositories in the world, with millions of available packages.
# Initialize a new project
npm init
# Install a package
npm install express
# Install a package globally
npm install -g nodemon
# Run scripts defined in package.json
npm run start
4. Modules
Node.js uses a module system to organize code into separate files, making maintenance and reusability easier.
// math.js module
exports.add = (a, b) => a + b;
exports.subtract = (a, b) => a - b;
// Using the module
const math = require('./math');
console.log(math.add(5, 3)); // 8
Node.js Architecture
1. V8 Engine
V8 is the open-source JavaScript engine developed by Google for Chrome. Node.js uses V8 to interpret and execute JavaScript code.
2. Libuv
Libuv is a cross-platform asynchronous I/O library that gives Node.js access to the file system, networking, and other operating system resources in a non-blocking way.
3. Native Modules
Node.js includes native modules written in C++ that provide low-level functionalities, such as file system access, networking, cryptography, etc.
4. JavaScript Modules
The Node.js standard library includes JavaScript modules that provide high-level functionalities, such as HTTP, HTTPS, FS (file system), etc.
Core Modules
1. HTTP/HTTPS
Allows creating HTTP servers and making HTTP requests.
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
});
server.listen(3000);
2. FS (File System)
Provides an API to interact with the file system.
const fs = require('fs');
// Synchronous read
const data = fs.readFileSync('file.txt', 'utf8');
console.log(data);
// Asynchronous read
fs.readFile('file.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
// Using Promises (Node.js 10+)
const fsPromises = require('fs').promises;
async function readFile() {
try {
const data = await fsPromises.readFile('file.txt', 'utf8');
console.log(data);
} catch (err) {
console.error(err);
}
}
3. Path
Provides utilities for working with file and directory paths.
const path = require('path');
// Join path segments
const fullPath = path.join('/directory', 'subdirectory', 'file.txt');
// Get the file name
const fileName = path.basename(fullPath);
// Get the file extension
const fileExt = path.extname(fullPath);
// Get the directory name
const dirName = path.dirname(fullPath);
4. Events
Provides an implementation of the Observer pattern through the EventEmitter class.
const EventEmitter = require('events');
class MyEmitter extends EventEmitter {}
const emitter = new MyEmitter();
// Register a listener
emitter.on('event', (a, b) => {
console.log(a, b);
});
// Emit an event
emitter.emit('event', 'a', 'b');
5. Stream
Provides an interface for working with data streams.
const fs = require('fs');
// Readable stream
const readStream = fs.createReadStream('file.txt');
readStream.on('data', (chunk) => {
console.log(`Received ${chunk.length} bytes of data.`);
});
readStream.on('end', () => {
console.log('Read finished.');
});
// Writable stream
const writeStream = fs.createWriteStream('output.txt');
writeStream.write('Hello, ');
writeStream.write('World!');
writeStream.end();
// Pipe (chaining streams)
readStream.pipe(writeStream);
Popular Frameworks and Libraries
1. Express
Express is a minimalist and flexible web framework for Node.js that provides a robust set of features for web and mobile applications.
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(port, () => {
console.log(`Application running at http://localhost:${port}`);
});
2. Nest.js
Nest.js is a framework for building efficient and scalable server-side applications in Node.js, inspired by Angular.
import { Controller, Get } from '@nestjs/common';
@Controller('cats')
export class CatsController {
@Get()
findAll(): string {
return 'This action returns all cats';
}
}
3. Socket.io
Socket.io is a library that enables real-time, bidirectional, and event-based communication between web browsers and servers.
const io = require('socket.io')(server);
io.on('connection', (socket) => {
console.log('A user connected');
socket.on('chat message', (msg) => {
io.emit('chat message', msg);
});
socket.on('disconnect', () => {
console.log('User disconnected');
});
});
4. Mongoose
Mongoose is a MongoDB object modeling library for Node.js.
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test');
const Cat = mongoose.model('Cat', { name: String });
const kitty = new Cat({ name: 'Zildjian' });
kitty.save().then(() => console.log('meow'));