npm package: @peaseernest/system-info
Description: Professional Node.js library for retrieving system information with actual usable data. Features beautiful console output powered by ernest-logger v2.0, TypeScript support, caching, monitoring, and health checks.
Author: Pease Ernest
Latest version: 2.0.0

# 🚀 System Info Pro

[![npm version](https://img.shields.io/npm/v/@peaseernest/system-info.svg)](https://www.npmjs.com/package/@peaseernest/system-info)
[![MIT License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
[![Node.js](https://img.shields.io/badge/node-%3E%3D14.0-green.svg)](https://nodejs.org/)
[![Powered by ernest-logger](https://img.shields.io/badge/powered%20by-ernest--logger-orange.svg)](https://www.npmjs.com/package/ernest-logger)

**A professional Node.js library for retrieving and working with system information.** Unlike other libraries that only log data, System Info Pro gives you **actual usable data** you can programmatically work with. Features beautiful console output powered by **ernest-logger v2.0** 🎨

## 🎯 Why This Library?

- ✅ **Returns actual data** - not just console logs
- ✅ **TypeScript support** - full type definitions
- ✅ **Real-time monitoring** - watch system metrics change
- ✅ **Health checks** - built-in health summary for APIs
- ✅ **Caching** - performance optimization built-in
- ✅ **Plugins** - extend with custom functionality
- ✅ **Zero config** - works out of the box

## 📦 Installation

```bash
npm install @peaseernest/system-info
```

**Optional dependencies** (install for full functionality):
```bash
npm install ping systeminformation ernest-logger
```

## 🚀 Quick Start

```javascript
const systemInfo = require('@peaseernest/system-info');

// Get memory info and USE it
const memory = await systemInfo.getMemory();
console.log(`Using ${memory.usedPercent}% of RAM`);

if (memory.usedPercent > 80) {
  console.log('⚠️ High memory usage!');
}

// Get everything at once
const all = await systemInfo.getAll();
console.log(all);
```

## 💡 Real-World Examples

### 1️⃣ Health Check API Endpoint

```javascript
app.get('/health', async (req, res) => {
  const health = await systemInfo.getHealthSummary();
  
  res.status(health.status === 'healthy' ? 200 : 503).json({
    status: health.status,
    memory: health.memory.usedPercent,
    cpu: health.cpu.usage,
    issues: health.issues,
    warnings: health.warnings
  });
});
```

### 2️⃣ Adaptive Task Scheduler

```javascript
async function scheduleTask() {
  const memory = await systemInfo.getMemory();
  const cpu = await systemInfo.getCpu();
  
  // Adjust concurrency based on system load
  const maxConcurrent = 
    (memory.usedPercent > 80 || cpu.usage > 80) ? 2 :
    (memory.usedPercent > 60 || cpu.usage > 60) ? 5 : 10;
  
  await runTasks(maxConcurrent);
}
```

### 3️⃣ Real-Time Monitoring Dashboard

```javascript
const stop = await systemInfo.monitor((err, data) => {
  const dashboard = {
    cpu: `${data.cpu.usage}%`,
    memory: `${data.memory.usedPercent}%`,
    uptime: data.basic.uptime.formatted
  };
  
  io.emit('system-update', dashboard);
}, 1000);
```

### 4️⃣ Export System Report

```javascript
const report = await systemInfo.getAll();
fs.writeFileSync('report.json', JSON.stringify(report, null, 2));
```

### 5️⃣ Send Metrics to Monitoring Service

```javascript
const data = await systemInfo.getAll();

await axios.post('https://monitoring.service/metrics', {
  host: data.basic.hostname,
  metrics: {
    'cpu.usage': data.cpu.usage,
    'memory.used': data.memory.usedPercent,
    'uptime': data.basic.uptimeSeconds
  }
});
```

## 📚 API Reference

### Data Retrieval Methods

All methods return **actual data objects** you can work with:

| Method | Returns | Description |
|--------|---------|-------------|
| `getBasic()` | `Promise<BasicInfo>` | Platform, arch, hostname, uptime, CPU count |
| `getMemory()` | `Promise<MemoryInfo>` | Total, used, free memory with percentages |
| `getCpu()` | `Promise<CpuInfo>` | CPU model, cores, speed, usage, load avg |
| `getLatency(host?)` | `Promise<LatencyInfo>` | Network latency to specified host |
| `getDisk()` | `Promise<DiskInfo>` | Disk usage information |
| `getBattery()` | `Promise<BatteryInfo>` | Battery level and charging status |
| `getNetwork()` | `Promise<NetworkInfo>` | Network interfaces and addresses |
| `getUser()` | `Promise<UserInfo>` | Current user information |
| `getAll(options?)` | `Promise<AllInfo>` | All system info in one call |
| `getAllCached(options?)` | `Promise<AllInfo>` | Cached version for performance |

### Utility Methods

| Method | Description |
|--------|-------------|
| `monitor(callback, interval?)` | Monitor system changes in real-time |
| `getHealthSummary()` | Get health status with warnings |
| `use(pluginFn)` | Add custom plugin |

### Legacy Logging Methods

For backward compatibility, logging methods are still available:

```javascript
await systemInfo.logBasic();
await systemInfo.logMemory();
await systemInfo.logCpu();
await systemInfo.logAll();
```

## 📊 Data Structures

### MemoryInfo
```typescript
{
  total: { value: 16, unit: 'GB', formatted: '16.00 GB' },
  used: { value: 8.5, unit: 'GB', formatted: '8.50 GB' },
  free: { value: 7.5, unit: 'GB', formatted: '7.50 GB' },
  usedPercent: 53.12,
  freePercent: 46.88,
  totalBytes: 17179869184,
  usedBytes: 9126805504,
  freeBytes: 8053063680
}
```

### CpuInfo
```typescript
{
  model: 'Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz',
  speed: 2600,
  cores: 12,
  usage: 23.5,
  loadAvg: { '1min': 1.2, '5min': 1.5, '15min': 1.8 },
  details: [/* per-core info */]
}
```

### BasicInfo
```typescript
{
  platform: 'linux',
  architecture: 'x64',
  hostname: 'server-01',
  uptime: { days: 5, hours: 12, minutes: 30, seconds: 45, formatted: '5d 12h 30m 45s' },
  uptimeSeconds: 476445,
  cpuCount: 12,
  nodeVersion: 'v18.17.0',
  processUptime: { /* same format as uptime */ },
  timestamp: 1699200000000
}
```

## 🔌 Plugin System

Extend functionality with custom plugins:

```javascript
systemInfo.use(async function customMetrics() {
  return {
    appVersion: require('./package.json').version,
    environment: process.env.NODE_ENV,
    activeConnections: await getActiveConnections()
  };
});

const data = await systemInfo.getAll();
console.log(data.plugins.customMetrics);
```

## ⚡ Performance & Caching

Use `getAllCached()` for better performance:

```javascript
// First call: fetches fresh data (~50ms)
const data1 = await systemInfo.getAllCached();

// Second call: returns cached data (~1ms)
const data2 = await systemInfo.getAllCached();

// Cache expires after 5 seconds
```

## 🏥 Health Monitoring

```javascript
const health = await systemInfo.getHealthSummary();

// Returns:
{
  status: 'healthy' | 'warning' | 'critical',
  issues: ['Memory usage critical: 95%'],
  warnings: ['CPU usage high: 78%'],
  memory: { /* MemoryInfo */ },
  cpu: { /* CpuInfo */ }
}
```

## 🔄 Real-Time Monitoring

```javascript
const stopMonitoring = await systemInfo.monitor((err, data) => {
  if (err) {
    console.error('Monitor error:', err);
    return;
  }
  
  console.log(`CPU: ${data.cpu.usage}%`);
  console.log(`Memory: ${data.memory.usedPercent}%`);
}, 1000); // Update every second

// Stop monitoring when done
stopMonitoring();
```

## 🎨 TypeScript Support

Full TypeScript definitions included:

```typescript
import systemInfo, { MemoryInfo, CpuInfo, AllInfo } from '@peaseernest/system-info';

const memory: MemoryInfo = await systemInfo.getMemory();
const cpu: CpuInfo = await systemInfo.getCpu();
```

## 🆚 Comparison with Original

| Feature | Original | Revamped |
|---------|----------|----------|
| Returns usable data | ❌ No | ✅ Yes |
| TypeScript types | ⚠️ Basic | ✅ Complete |
| Real-time monitoring | ❌ No | ✅ Yes |
| Health checks | ❌ No | ✅ Yes |
| Caching | ❌ No | ✅ Yes |
| Plugin system | ⚠️ Basic | ✅ Enhanced |
| Data structures | ⚠️ Strings only | ✅ Rich objects |
| Async/await | ⚠️ Inconsistent | ✅ All async |

## 📝 Migration Guide

### Old Way (v1.0)
```javascript
// Could only log, no data access
systemInfo.logMemoryInfo();
// No way to get the actual values!
```

### New Way (v2.0)
```javascript
// Get actual data
const memory = await systemInfo.getMemory();
console.log(memory.usedPercent); // 53.12

// Still supports logging if you want it
await systemInfo.logMemory();
```

## 🛠️ Advanced Usage

### Custom Formatting
```javascript
const memory = await systemInfo.getMemory();
const formatted = `${memory.used.value.toFixed(1)}${memory.used.unit} / ${memory.total.formatted}`;
// "8.5GB / 16.00 GB"
```

### Conditional Logic
```javascript
const data = await systemInfo.getAll();

if (data.memory.usedPercent > 90) {
  await scaleUpServers();
} else if (data.memory.usedPercent < 30) {
  await scaleDownServers();
}
```

### Integration with Express
```javascript
const express = require('express');
const systemInfo = require('@peaseernest/system-info');

const app = express();

app.get('/api/system', async (req, res) => {
  const data = await systemInfo.getAllCached();
  res.json(data);
});

app.get('/api/health', async (req, res) => {
  const health = await systemInfo.getHealthSummary();
  res.status(health.status === 'healthy' ? 200 : 503).json(health);
});
```

## 🤝 Contributing

Contributions welcome! Please open an issue before submitting PRs for new features.

### Bug Fixes
Always welcome via PR.

### New Features
Please open an issue first to discuss the feature.

## 📄 License

MIT © Ernest Tech House

## 🙏 Acknowledgments

Built with:
- Node.js core modules (`os`, `child_process`)
- `systeminformation` - Enhanced system info
- `ping` - Network latency
- `ernest-logger` - Styled logging

---

**Made with ❤️ by Pease Ernest**