stack-performance
Version:
A comprehensive application stack analyzer that evaluates MEAN, MERN, and other Node.js-based applications across 15 performance criteria
310 lines (251 loc) • 9.17 kB
Markdown
# Stack Performance Analyzer - Usage Examples
This document provides comprehensive examples of how to use the Stack Performance Analyzer.
## 🚀 Quick Start
```bash
# Install dependencies
npm install
# Analyze current directory (most common usage)
node index.js
# Or use the CLI
node bin/cli.js
```
## 📊 Sample Analysis Output
Here's what the analyzer produces when analyzing a Node.js project:
```
🚀 Starting Stack Performance Analysis...
📊 STACK PERFORMANCE ANALYSIS RESULTS
============================================================
Application Performance | 58/100 | Poor
Developer Productivity | 71/100 | Average
API Response Time | 61/100 | Average
Learning Curve | 75/100 | Good
Security Features | 75/100 | Good
Tooling & Ecosystem Support | 75/100 | Good
Integration with MongoDB | 75/100 | Good
Modularity & Scalability | 75/100 | Good
Package Ecosystem | 75/100 | Good
Startup Time | 75/100 | Good
Maintenance and Debugging | 75/100 | Good
Hosting and Deployment Flexibility | 75/100 | Good
Memory & CPU Efficiency | 75/100 | Good
Performance under Concurrent Load | 75/100 | Good
Monitoring and Observability | 75/100 | Good
------------------------------------------------------------
OVERALL PERFORMANCE | 79/100 | Good
✅ Analysis Complete
🔧 Detected Stack Information:
Stack Type: Node.js Application
Technologies: Node.js
Node.js Version: >=14.0.0
```
## 🎯 How the Algorithmic Scoring Works
### Application Performance (Example)
The analyzer uses **multiple weighted factors**, NOT random numbers:
1. **Framework Performance (30% weight)**:
- Express.js: +15 points (lightweight, performant)
- Fastify: +20 points (highly optimized)
- React SSR capability: +5 points
2. **Code Structure Analysis (25% weight)**:
- Analyzes actual code files for complexity
- Average lines per file < 100: +15 points
- High complexity patterns: -15 points
- Async/await usage: +3 points each file
3. **Database Integration (20% weight)**:
- Mongoose presence: +15 points
- Connection pooling config: +5 points
- Database indexing patterns: +3 points
4. **Asset Management (15% weight)**:
- Webpack configuration: +15 points
- Optimization config detected: +10 points
- Minification tools: +8 points
5. **Caching Implementation (10% weight)**:
- Redis: +20 points
- HTTP cache headers: +10 points
- In-memory caching: +10 points
**Final Score = Weighted Average of All Factors**
### Developer Productivity Analysis
1. **Tooling Support (40%)**:
- ESLint: +10 points
- Prettier: +8 points
- TypeScript: +12 points
- Jest/Testing: +8 points
- Nodemon: +5 points
2. **Learning Curve (30%)**:
- Express.js: +15 points (easy to learn)
- React: +10 points (good documentation)
- Angular: -5 points (steeper curve)
3. **Community Support (20%)**:
- Dependency count analysis
- Popular framework detection
- Ecosystem maturity assessment
4. **Code Reusability (10%)**:
- Modular structure detection
- Component-based architecture
- TypeScript bonus points
## 📁 Analyzing Different Project Types
### MERN Stack Project
```bash
# Sample package.json that would score highly:
{
"dependencies": {
"express": "^4.18.0",
"mongoose": "^6.3.0",
"react": "^18.0.0",
"react-dom": "^18.0.0"
},
"devDependencies": {
"eslint": "^8.0.0",
"prettier": "^2.7.0",
"jest": "^28.0.0",
"nodemon": "^2.0.0"
}
}
# Would detect: MERN Stack (High scores for ecosystem)
# Application Performance: 85+/100
# Developer Productivity: 90+/100
```
### MEAN Stack Project
```bash
# With Angular instead of React:
{
"dependencies": {
"express": "^4.18.0",
"mongoose": "^6.3.0",
"@angular/core": "^14.0.0"
}
}
# Would detect: MEAN Stack
# Learning Curve: 75/100 (Angular is more complex)
# But still high overall performance
```
### Performance-Optimized Setup
```bash
{
"dependencies": {
"fastify": "^4.0.0", # +20 performance points
"mongoose": "^6.3.0",
"compression": "^1.7.4", # +30 compression points
"helmet": "^5.1.0", # +25 security points
"redis": "^4.1.0" # +20 caching points
},
"devDependencies": {
"webpack": "^5.0.0", # +15 asset points
"eslint": "^8.0.0", # +10 tooling points
"typescript": "^4.7.0" # +12 tooling points
}
}
# Would achieve 90+ overall performance
```
## 🔍 Advanced Usage
### JSON Output for CI/CD
```bash
# Get JSON results for automation
node bin/cli.js . --output json > results.json
# Save detailed analysis
node bin/cli.js . --save detailed-analysis.json
# Parse specific scores programmatically
node -e "
const results = require('./analysis-results.json');
console.log('Security Score:', results.criteria.find(c => c.name.includes('Security')).score);
console.log('Performance Score:', results.criteria.find(c => c.name.includes('Application Performance')).score);
"
```
### Programmatic Usage
```javascript
const ApplicationAnalyzer = require('./index');
async function analyzeProject(projectPath) {
const analyzer = new ApplicationAnalyzer({ projectPath });
const results = await analyzer.analyze();
// Get specific criterion scores
const performanceScore = results.criteria
.find(c => c.name === 'Application Performance')?.score || 0;
const securityScore = results.criteria
.find(c => c.name.includes('Security'))?.score || 0;
// Make decisions based on scores
if (performanceScore < 70) {
console.log('⚠️ Performance needs improvement');
console.log('Recommendations:', results.criteria.find(c => c.name === 'Application Performance').recommendations);
}
if (securityScore < 80) {
console.log('🔒 Security enhancements needed');
}
return {
overall: results.overall.score,
performance: performanceScore,
security: securityScore,
passed: results.overall.score >= 75
};
}
// Usage
analyzeProject('./my-project')
.then(summary => {
console.log('Analysis Summary:', summary);
process.exit(summary.passed ? 0 : 1); // Exit code for CI/CD
});
```
### Batch Analysis
```bash
# Analyze multiple projects
for project in project1 project2 project3; do
echo "Analyzing $project..."
node bin/cli.js "./$project" --save "results-$project.json"
done
# Compare results
node -e "
const fs = require('fs');
['project1', 'project2', 'project3'].forEach(p => {
const results = JSON.parse(fs.readFileSync(\`results-\${p}.json\`));
console.log(\`\${p}: \${results.overall.score}/100 (\${results.overall.remark})\`);
});
"
```
## ⚙️ Customization
### Environment-Specific Analysis
```javascript
// Custom analyzer with different weights
const analyzer = new ApplicationAnalyzer({
projectPath: './my-app',
// Could extend to support custom weights
});
```
### Integration with Build Tools
```json
// package.json scripts
{
"scripts": {
"analyze": "node bin/cli.js",
"analyze:ci": "node bin/cli.js --output json --save build/analysis.json",
"analyze:verbose": "node bin/cli.js --verbose",
"test:performance": "node bin/cli.js && echo 'Performance analysis passed'"
}
}
```
## 🎯 Score Interpretation
| Score Range | Remark | Meaning |
|------------|---------|---------|
| 95-100 | Excellent | Industry best practices, highly optimized |
| 85-94 | Best | Well-implemented with minor areas for improvement |
| 75-84 | Good | Solid implementation, some optimization opportunities |
| 60-74 | Average | Basic implementation, several improvement areas |
| 0-59 | Poor | Significant issues, major improvements needed |
## 🔧 Troubleshooting
### Common Issues
1. **No package.json found**:
```bash
# Ensure you're in a Node.js project directory
ls package.json
```
2. **Low Application Performance scores**:
- Add build optimization tools (Webpack, Vite)
- Implement caching strategies (Redis)
- Optimize code structure and complexity
3. **Low Security scores**:
- Add security middleware (Helmet)
- Implement input validation (Joi, Express-validator)
- Add authentication libraries (Passport, JWT)
### Performance Tips
1. **For MERN/MEAN stacks**: Include all standard dependencies
2. **For performance**: Use Fastify instead of Express
3. **For developer productivity**: Add TypeScript, ESLint, Prettier
4. **For security**: Include Helmet, validation libraries, rate limiting
This analyzer provides actionable insights based on **real code analysis** and **industry best practices**, not random numbers. Use it to identify specific areas for improvement in your Node.js applications!