Node.js Coding Examples
Example 1: Basic HTTP Server
const http = require('http'); // Create an HTTP server const server = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Hello World\n'); }); // Server listens on port 3000 server.listen(3000, '127.0.0.1', () => { console.log('Server running at http://127.0.0.1:3000/'); });
"The best way to predict the future is to invent it." – Alan Kay
Example 2: Reading a File
const fs = require('fs'); // Read file asynchronously fs.readFile('example.txt', 'utf8', (err, data) => { if (err) { console.error(err); return; } console.log(data); });
"Simplicity is the soul of efficiency." – Austin Freeman
Example 3: Writing to a File
const fs = require('fs'); // Write to a file asynchronously fs.writeFile('example.txt', 'Hello, world!', (err) => { if (err) { console.error(err); return; } console.log('File written successfully'); });
"Code is like humor. When you have to explain it, it’s bad." – Cory House
Example 4: HTTP Request with `axios`
const axios = require('axios'); // Make a GET request axios.get('https://api.github.com/users/octocat') .then(response => { console.log(response.data); }) .catch(error => { console.error('Error:', error); });
"The most disastrous thing that you can ever learn is your first programming language." – Alan Perlis
Example 5: Express Server Setup
const express = require('express'); const app = express(); // Define a route app.get('/', (req, res) => { res.send('Hello World!'); }); // Start the server app.listen(3000, () => { console.log('Server is running on http://localhost:3000'); });
"The only way to do great work is to love what you do." – Steve Jobs
Example 6: Using Promises
const fs = require('fs').promises; // Asynchronous function to read a file async function readFile() { try { const data = await fs.readFile('example.txt', 'utf8'); console.log(data); } catch (err) { console.error(err); } } readFile();
"Programming isn't about what you know; it's about what you can figure out." – Chris Pine
Example 7: Event Emitter
const EventEmitter = require('events'); const myEmitter = new EventEmitter(); // Add an event listener myEmitter.on('event', (message) => { console.log(`Event occurred: ${message}`); }); // Emit an event myEmitter.emit('event', 'Hello World!');
"You can’t have great software without a great team." – Jeff Sutherland
Example 8: Mongoose with MongoDB
const mongoose = require('mongoose'); // Connect to MongoDB mongoose.connect('mongodb://localhost:27017/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true }); const Schema = mongoose.Schema; const userSchema = new Schema({ name: String, age: Number }); const User = mongoose.model('User', userSchema); // Create and save a new user const newUser = new User({ name: 'Alice', age: 30 }); newUser.save() .then(() => console.log('User added')) .catch(err => console.error(err));
"Good code is its own best documentation." – Steve McConnell
Example 9: Handling JSON Data
const jsonData = '{"name": "Ayşe", "age": 25}'; const data = JSON.parse(jsonData); console.log(`Name: ${data.name}, Age: ${data.age}`); // Convert object to JSON string const newData = JSON.stringify(data); console.log(newData);
"The most important property of a program is whether it accomplishes the intention of its user." – Peter G. Neumark
Example 10: Reading User Input
const readline = require('readline'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); // Prompt user for input rl.question('What is your name? ', (answer) => { console.log(`Hello, ${answer}!`); rl.close(); });
"The code you write makes you a programmer. The code you don’t write makes you a good programmer." – Anonymous
Example 11: Database Connection
const mysql = require('mysql'); // Create a MySQL connection const connection = mysql.createConnection({ host: 'localhost', user: 'user', password: 'password', database: 'mydatabase' }); connection.connect(err => { if (err) { console.error('Error connecting: ' + err.stack); return; } console.log('Connected as id ' + connection.threadId); }); // Perform a query connection.query('SELECT * FROM users', (err, results) => { if (err) throw err; console.log(results); }); // Close the connection connection.end();
"If you don’t know how to do something, just do it. You will learn by doing." – Rob Pike
Example 12: Using Async/Await
const fs = require('fs').promises; async function readFile() { try { const data = await fs.readFile('example.txt', 'utf8'); console.log(data); } catch (err) { console.error(err); } } readFile();
"The purpose of software engineering is to control complexity, not to create it." – Pamela Zave
Example 13: Rate Limiting
const express = require('express'); const rateLimit = require('express-rate-limit'); const app = express(); const limiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 100 }); app.use(limiter); app.get('/', (req, res) => { res.send('Rate limiting applied.'); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
"Testing leads to failure, and failure leads to understanding." – Burt Rutan
Example 14: Using WebSockets
const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', (ws) => { console.log('New connection'); ws.on('message', (message) => { console.log(`Received message: ${message}`); }); ws.send('Welcome!'); });
"If you want to be a good programmer, you should read code." – Anonymous
Example 15: Middleware in Express
const express = require('express'); const app = express(); // Middleware function app.use((req, res, next) => { console.log('Middleware executed'); next(); }); app.get('/', (req, res) => { res.send('Hello World with Middleware!'); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
"In software engineering, there are no shortcuts to success." – Michael Feathers
Example 16: SetInterval and SetTimeout
// Set an interval to log a message every second const intervalId = setInterval(() => { console.log('This message appears every second'); }, 1000); // Set a timeout to clear the interval after 5 seconds setTimeout(() => { clearInterval(intervalId); console.log('Interval cleared'); }, 5000);
"It is not the strongest of the species that survive, nor the most intelligent, but the one most responsive to change." – Charles Darwin
Example 17: Sending Data with HTTP Request
const http = require('http'); const postData = JSON.stringify({ name: 'John', age: 30 }); const options = { hostname: 'www.example.com', port: 80, path: '/data', method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': postData.length } }; const req = http.request(options, (res) => { res.on('data', (chunk) => { console.log(`Received data: ${chunk}`); }); }); req.on('error', (e) => { console.error(`Problem with request: ${e.message}`); }); req.write(postData); req.end();
"It’s not a bug; it’s an undocumented feature." – Anonymous
Example 18: Compressing and Archiving Files
const zlib = require('zlib'); const fs = require('fs'); const input = fs.createReadStream('file.txt'); const output = fs.createWriteStream('file.txt.gz'); input.pipe(zlib.createGzip()).pipe(output); output.on('finish', () => { console.log('File successfully compressed.'); });
"Simplicity is the ultimate sophistication." – Leonardo da Vinci
Example 19: Using Environment Variables
require('dotenv').config(); const dbHost = process.env.DB_HOST; const dbPort = process.env.DB_PORT; console.log(`Database host: ${dbHost}:${dbPort}`);
"It’s not the tools you use; it’s how you use them." – Anonymous
Example 20: Basic WebSocket Server
const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', (ws) => { console.log('New connection'); ws.on('message', (message) => { console.log(`Received message: ${message}`); }); ws.send('Welcome!'); });
"The best way to learn is by doing." – Anonymous
Example 21: Load Balancing with Cluster
const cluster = require('cluster'); const http = require('http'); const numCPUs = require('os').cpus().length; if (cluster.isMaster) { // Fork workers for (let i = 0; i < numCPUs; i++) { cluster.fork(); } cluster.on('exit', (worker, code, signal) => { console.log(`Worker ${worker.process.pid} died`); }); } else { http.createServer((req, res) => { res.writeHead(200); res.end('Hello World!\n'); }).listen(8000); }
"Good software, like wine, takes time." – Anonymous
Example 22: File Upload with Multer
const express = require('express'); const multer = require('multer'); const path = require('path'); const app = express(); const upload = multer({ dest: 'uploads/' }); app.post('/upload', upload.single('file'), (req, res) => { res.send('File uploaded!'); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
"The best code is no code at all." – Jeff Atwood
Example 23: Caching with Node.js
const NodeCache = require('node-cache'); const myCache = new NodeCache(); // Set a cache value myCache.set('key', 'value', 10000); // Get a cache value const value = myCache.get('key'); if (value == undefined) { console.log('Cache value not found'); } else { console.log(`Cache value: ${value}`); }
"There are only two hard things in computer science: cache invalidation and naming things." – Phil Karlton
Example 24: Connecting to a Redis Database
const redis = require('redis'); const client = redis.createClient(); client.on('error', (err) => { console.log('Redis error: ' + err); }); // Set a value client.set('key', 'value', redis.print); // Get a value client.get('key', (err, reply) => { if (err) throw err; console.log('Value: ' + reply); });
"The best way to understand how a program works is to try to write it yourself." – Anonymous
Example 25: Validating Input with Joi
const Joi = require('joi'); // Define a schema const schema = Joi.object({ name: Joi.string().min(3).required(), age: Joi.number().integer().min(0).required() }); // Validate input const result = schema.validate({ name: 'Alice', age: 30 }); if (result.error) { console.error(result.error.details); } else { console.log('Validation succeeded'); }
"Software is a great combination between artistry and engineering." – Bill Gates
Example 26: WebSocket Chat Server
const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); const players = {}; wss.on('connection', (ws) => { console.log('New player connected'); ws.on('message', (message) => { console.log(`Received message: ${message}`); // Broadcast message to other players for (const [id, playerWs] of Object.entries(players)) { if (playerWs !== ws) { playerWs.send(message); } } }); ws.on('close', () => { console.log('A player disconnected'); // Remove player from list for (const [id, playerWs] of Object.entries(players)) { if (playerWs === ws) { delete players[id]; } } }); // Add player const playerId = Date.now(); players[playerId] = ws; ws.send(`Welcome player ${playerId}`); });
"The greatest danger in times of turbulence is not the turbulence; it is to act with yesterday’s logic." – Peter Drucker
Example 27: Using LevelDB
const level = require('level'); const db = level('./mydb', { valueEncoding: 'json' }); // Put data into the database db.put('key', { name: 'Mehmet', age: 40 }, (err) => { if (err) return console.error('Error adding data:', err); // Get data from the database db.get('key', (err, value) => { if (err) return console.error('Error retrieving data:', err); console.log('Value:', value); }); });
"Software development is a continual process of learning and adaptation." – Tim Berners-Lee
Example 28: Handling Errors
const fs = require('fs'); // Read a file and handle potential errors fs.readFile('example.txt', 'utf8', (err, data) => { if (err) { console.error('Error reading file:', err.message); return; } console.log('File content:', data); });
"In programming, the hardest part is thinking." – John Backus
Example 29: Using `process.env` for Configuration
const express = require('express'); const app = express(); // Use environment variables for configuration const port = process.env.PORT || 3000; app.get('/', (req, res) => { res.send('Hello World with environment variables!'); }); app.listen(port, () => { console.log(`Server running on http://localhost:${port}`); });
"Programmers are constantly making decisions and solving problems, often on the fly." – James Gosling
Example 30: Creating an HTTP Server with `http2`
const http2 = require('http2'); const fs = require('fs'); // Create an HTTP/2 server const server = http2.createSecureServer({ key: fs.readFileSync('server.key'), cert: fs.readFileSync('server.crt') }); server.on('stream', (stream) => { stream.respond({ 'content-type': 'text/plain' }); stream.end('Hello World\n'); }); server.listen(8443, () => { console.log('HTTP/2 server running on https://localhost:8443'); });
"The only way to improve is to keep learning and experimenting." – Anonymous