#Lab 03: Node.js DevOps Utilities
Build DevOps utility scripts with Node.js.
#šÆ Objectives
- Create a deployment notification script
- Build a log analyzer utility
- Handle async operations properly
#š Prerequisites
- Node.js 18+ installed
- npm knowledge
#š¬ Lab Steps
#Step 1: Project Setup
bash
1mkdir devops-utils
2cd devops-utils
3npm init -y
4npm install axios chalk commander dotenv yaml#Step 2: Create Deployment Notifier
Create notify.js:
javascript
1#!/usr/bin/env node
2
3const axios = require('axios');
4const chalk = require('chalk');
5
6async function sendSlackNotification(webhookUrl, message) {
7 try {
8 await axios.post(webhookUrl, {
9 text: message,
10 username: 'Deploy Bot',
11 icon_emoji: ':rocket:'
12 });
13 console.log(chalk.green('ā
Notification sent!'));
14 } catch (error) {
15 console.error(chalk.red('ā Failed:', error.message));
16 }
17}
18
19async function main() {
20 const environment = process.argv[2] || 'staging';
21 const version = process.argv[3] || 'latest';
22
23 const message = `š *Deployment Complete*
24Environment: ${environment}
25Version: ${version}
26Time: ${new Date().toISOString()}`;
27
28 console.log(chalk.blue('Deployment Notification:'));
29 console.log(message);
30
31 // Uncomment with real webhook URL
32 // await sendSlackNotification(process.env.SLACK_WEBHOOK, message);
33}
34
35main();#Step 3: Create Log Analyzer
Create analyze-logs.js:
javascript
1#!/usr/bin/env node
2
3const fs = require('fs').promises;
4const chalk = require('chalk');
5
6async function analyzeLogs(logFile) {
7 const content = await fs.readFile(logFile, 'utf-8');
8 const lines = content.split('\n').filter(Boolean);
9
10 const stats = {
11 total: lines.length,
12 errors: 0,
13 warnings: 0,
14 info: 0
15 };
16
17 for (const line of lines) {
18 if (line.includes('ERROR')) stats.errors++;
19 else if (line.includes('WARN')) stats.warnings++;
20 else if (line.includes('INFO')) stats.info++;
21 }
22
23 console.log(chalk.bold('\nš Log Analysis Report\n'));
24 console.log(`Total Lines: ${stats.total}`);
25 console.log(chalk.red(`Errors: ${stats.errors}`));
26 console.log(chalk.yellow(`Warnings: ${stats.warnings}`));
27 console.log(chalk.blue(`Info: ${stats.info}`));
28
29 return stats;
30}
31
32const logFile = process.argv[2] || 'app.log';
33analyzeLogs(logFile).catch(console.error);#Step 4: Run the Utilities
bash
1# Create sample log
2echo "2024-01-01 INFO Starting server
32024-01-01 ERROR Database connection failed
42024-01-01 WARN High memory usage
52024-01-01 INFO Request processed" > app.log
6
7# Run analyzer
8node analyze-logs.js app.log
9
10# Run notifier
11node notify.js production v1.2.3#ā Success Criteria
- Scripts run without errors
- Log analyzer counts correctly
- Notification format is clear
#š What You Learned
- Node.js file operations
- HTTP requests with axios
- CLI argument handling
- Async/await patterns