Master Node.js fundamentals with our comprehensive tutorial. Learn through examples and hands-on practice.
Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine that allows you to run JavaScript on the server side.
console.log('Hello from Node.js');
// Basic HTTP Server
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World
');
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
A simple Node.js HTTP server example
Node.js uses a modular system to organize code into reusable components.
// math.js
module.exports = {
add: (a, b) => a + b,
subtract: (a, b) => a - b,
multiply: (a, b) => a * b
};
// main.js
const math = require('./math');
console.log(math.add(5, 3)); // Output: 8
console.log(math.multiply(2, 4)); // Output: 8
Creating and using custom modules in Node.js
Node.js excels at handling asynchronous operations using callbacks, promises, and async/await.
// Using async/await
const fs = require('fs').promises;
async function readFile() {
try {
const data = await fs.readFile('example.txt', 'utf8');
console.log(data);
} catch (error) {
console.error('Error reading file:', error);
}
}
readFile();
Reading a file asynchronously using async/await