Learn Node.js fundamentals including event loop, asynchronous programming, modules, and file system operations.
Learn Node.js fundamentals including event loop, asynchronous programming, modules, and file system operations.
Understanding Node.js architecture, runtime environment, and its role in modern web development
Content by: Parth Patel
Node.js Developer
Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. It allows you to run JavaScript on the server-side, enabling full-stack JavaScript development. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient.
// Check Node.js version
node --version
// Check NPM version
npm --version
// Create a new Node.js project
mkdir my-node-app
cd my-node-app
npm init -y
// Install dependencies
npm install express
// Basic Node.js 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/');
});
Test your understanding of this topic:
Master Node.js event loop and asynchronous programming patterns with callbacks, promises, and async/await
Content by: Bansi Patel
Node.js Developer
The event loop is the core of Node.js's asynchronous, non-blocking I/O model. It allows Node.js to perform non-blocking I/O operations despite JavaScript being single-threaded. The event loop continuously checks for pending operations and executes them when they're ready.
// Callback pattern
const fs = require('fs');
fs.readFile('file.txt', 'utf8', (err, data) => {
if (err) {
console.error('Error reading file:', err);
return;
}
console.log('File content:', data);
});
// Promise pattern
const fs = require('fs').promises;
fs.readFile('file.txt', 'utf8')
.then(data => {
console.log('File content:', data);
})
.catch(err => {
console.error('Error reading file:', err);
});
// Async/await pattern
const fs = require('fs').promises;
async function readFile() {
try {
const data = await fs.readFile('file.txt', 'utf8');
console.log('File content:', data);
} catch (err) {
console.error('Error reading file:', err);
}
}
readFile();
// Event emitter pattern
const EventEmitter = require('events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
myEmitter.on('event', (arg) => {
console.log('Event occurred with argument:', arg);
});
myEmitter.emit('event', 'Hello World!');
Test your understanding of this topic:
Learn Node.js module system, CommonJS vs ES modules, and NPM package management
Content by: Raj Koradiya
Node.js Developer
Node.js has a built-in module system that allows you to organize your code into reusable pieces. Modules help you create maintainable and scalable applications by separating concerns and avoiding global scope pollution.
// math.js - Exporting modules
const add = (a, b) => a + b;
const subtract = (a, b) => a - b;
const multiply = (a, b) => a * b;
const divide = (a, b) => a / b;
// Export individual functions
module.exports.add = add;
module.exports.subtract = subtract;
// Export as an object
module.exports = {
add,
subtract,
multiply,
divide
};
// app.js - Importing modules
const math = require('./math');
console.log(math.add(5, 3)); // 8
console.log(math.subtract(10, 4)); // 6
console.log(math.multiply(2, 6)); // 12
console.log(math.divide(15, 3)); // 5
// Destructuring imports
const { add, subtract } = require('./math');
console.log(add(5, 3)); // 8
console.log(subtract(10, 4)); // 6
// math.js - ES Module exports
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
export const multiply = (a, b) => a * b;
export const divide = (a, b) => a / b;
// Default export
const calculator = {
add,
subtract,
multiply,
divide
};
export default calculator;
// app.js - ES Module imports
import { add, subtract, multiply, divide } from './math.js';
import calculator from './math.js';
console.log(add(5, 3)); // 8
console.log(calculator.multiply(2, 6)); // 12
// Dynamic imports
async function loadModule() {
const math = await import('./math.js');
console.log(math.add(5, 3));
}
loadModule();
// Initialize a new project
npm init -y
// Install dependencies
npm install express
npm install --save-dev nodemon
// Install specific version
npm install express@4.18.2
// Install globally
npm install -g nodemon
// Remove package
npm uninstall express
// Update packages
npm update
// List installed packages
npm list
// Run scripts
npm start
npm test
npm run dev
// package.json example
{
"name": "my-node-app",
"version": "1.0.0",
"description": "A Node.js application",
"main": "index.js",
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js",
"test": "jest"
},
"dependencies": {
"express": "^4.18.2"
},
"devDependencies": {
"nodemon": "^2.0.22"
}
}
Test your understanding of this topic:
Learn to work with files and directories using Node.js fs module
Content by: Prakash Patel
Node.js Developer
The fs module provides an API for interacting with the file system. It supports both synchronous and asynchronous operations, with the asynchronous versions being preferred for better performance.
const fs = require('fs');
// Synchronous file reading
try {
const data = fs.readFileSync('file.txt', 'utf8');
console.log('File content:', data);
} catch (err) {
console.error('Error reading file:', err);
}
// Asynchronous file reading
fs.readFile('file.txt', 'utf8', (err, data) => {
if (err) {
console.error('Error reading file:', err);
return;
}
console.log('File content:', data);
});
// Using promises
const fs = require('fs').promises;
async function readFile() {
try {
const data = await fs.readFile('file.txt', 'utf8');
console.log('File content:', data);
} catch (err) {
console.error('Error reading file:', err);
}
}
readFile();
// Reading JSON files
const fs = require('fs').promises;
async function readJSON() {
try {
const data = await fs.readFile('config.json', 'utf8');
const config = JSON.parse(data);
console.log('Config:', config);
} catch (err) {
console.error('Error reading JSON:', err);
}
}
readJSON();
const fs = require('fs');
// Synchronous file writing
try {
fs.writeFileSync('output.txt', 'Hello World!');
console.log('File written successfully');
} catch (err) {
console.error('Error writing file:', err);
}
// Asynchronous file writing
fs.writeFile('output.txt', 'Hello World!', (err) => {
if (err) {
console.error('Error writing file:', err);
return;
}
console.log('File written successfully');
});
// Using promises
const fs = require('fs').promises;
async function writeFile() {
try {
await fs.writeFile('output.txt', 'Hello World!');
console.log('File written successfully');
} catch (err) {
console.error('Error writing file:', err);
}
}
writeFile();
// Appending to files
const fs = require('fs').promises;
async function appendToFile() {
try {
await fs.appendFile('log.txt', 'New log entry\n');
console.log('Log entry added');
} catch (err) {
console.error('Error appending to file:', err);
}
}
appendToFile();
// Writing JSON files
const fs = require('fs').promises;
async function writeJSON() {
const data = {
name: 'John Doe',
age: 30,
city: 'New York'
};
try {
await fs.writeFile('user.json', JSON.stringify(data, null, 2));
console.log('JSON file written successfully');
} catch (err) {
console.error('Error writing JSON:', err);
}
}
writeJSON();
const fs = require('fs');
// Creating directories
fs.mkdir('new-directory', (err) => {
if (err) {
console.error('Error creating directory:', err);
return;
}
console.log('Directory created successfully');
});
// Reading directory contents
fs.readdir('.', (err, files) => {
if (err) {
console.error('Error reading directory:', err);
return;
}
console.log('Files in directory:', files);
});
// Checking if file/directory exists
fs.access('file.txt', fs.constants.F_OK, (err) => {
if (err) {
console.log('File does not exist');
} else {
console.log('File exists');
}
});
// Getting file stats
fs.stat('file.txt', (err, stats) => {
if (err) {
console.error('Error getting file stats:', err);
return;
}
console.log('File size:', stats.size);
console.log('Is file:', stats.isFile());
console.log('Is directory:', stats.isDirectory());
console.log('Created:', stats.birthtime);
console.log('Modified:', stats.mtime);
});
// Using promises for directory operations
const fs = require('fs').promises;
async function directoryOperations() {
try {
// Create directory
await fs.mkdir('new-directory');
console.log('Directory created');
// Read directory
const files = await fs.readdir('.');
console.log('Files:', files);
// Check if file exists
try {
await fs.access('file.txt');
console.log('File exists');
} catch {
console.log('File does not exist');
}
// Get file stats
const stats = await fs.stat('file.txt');
console.log('File size:', stats.size);
} catch (err) {
console.error('Error:', err);
}
}
directoryOperations();
Test your understanding of this topic:
Continue your learning journey and master the next set of concepts.
Continue to Module 2