ओएस मॉड्यूल क्या है?
Node.js OS .
यह क्रॉस-प्लेटफ़ॉर्म तरीके से सिस्टम से संबंधित जानकारी तक पहुंच प्रदान करता है और सामान्य ऑपरेटिंग सिस्टम कार्य करता है।
कम्प्यूटर की जानकारी प्राप्त करना
सीपीयू, मेमोरी, प्लेटफ़ॉर्म, आदि
उपयोगकर्ता और नेटवर्क जानकारी
उपयोगकर्ता प्रोफ़ाइल और नेटवर्क इंटरफ़ेस
कंप्यूटर संसाधनों की निगरानी करना
प्रदर्शन और संसाधन उपयोग की निगरानी करना
ओएस मॉड्यूल के साथ शुरुआत करना
मॉड्यूल आयात कर रहा है
OS मॉड्यूल Node.js का एक महत्वपूर्ण मॉड्यूल है, इसलिए किसी इंस्टॉलेशन की आवश्यकता नहीं है।
आप CommonJS या ES मॉड्यूल व्याकरण का उपयोग कर सकते हैं और इसे आयात कर सकते हैं:
CommonJS (Node.js में डिफ़ॉल्ट)
const os = require('os');
ES Modules (Node.js 14+ or with "type": "module" in package.json)
import os from 'os';
// or
import { arch, platform, cpus } from 'os';
बुनियादी उपयोग उदाहरण
const os = require('os');
// Basic system information
console.log(`OS Platform: ${os.platform()}`);
console.log(`OS Type: ${os.type()}`);
console.log(`OS Release: ${os.release()}`);
console.log(`CPU Architecture: ${os.arch()}`);
console.log(`Hostname: ${os.hostname()}`);
// Memory information
const totalMemGB = (os.totalmem() / (1024 * 1024 * 1024)).toFixed(2);
const freeMemGB = (os.freemem() / (1024 * 1024 * 1024)).toFixed(2);
console.log(`Memory: ${freeMemGB}GB free of ${totalMemGB}GB`);
// User information
const userInfo = os.userInfo();
console.log(`Current User: ${userInfo.username}`);
console.log(`Home Directory: ${os.homedir()}`);
ओएस मॉड्यूल नोट:
सभी ओएस बैच विधियां सुसंगत हैं और तत्काल परिणाम प्रदान करती हैं।
प्रदर्शन-महत्वपूर्ण अनुप्रयोगों के लिए, अक्सर कहे जाने वाले तरीकों जैसे os.cpus() या os.networkInterfaces() के परिणामों को कैशिंग करने पर विचार करें।
कंप्यूटर की जानकारी
os.arch()
Node.js CPU .
const os = require('os');
// Get CPU architecture
console.log(`CPU Architecture: ${os.arch()}`);
// Common values:
// - 'x64' for 64-bit systems
// - 'arm' for ARM processors
// - 'arm64' for 64-bit ARM
// - 'ia32' for 32-bit x86
// - 'mips' for MIPS processors
os.platform()
ऑपरेटिंग सिस्टम प्लेटफ़ॉर्म की पहचान करने वाली एक स्ट्रिंग लौटाता है।
const os = require('os');
// Get platform information
const platform = os.platform();
console.log(`Platform: ${platform}`);
// Common values:
// - 'darwin' for macOS
// - 'win32' for Windows (both 32-bit and 64-bit)
// - 'linux' for Linux
// - 'freebsd' for FreeBSD
// - 'openbsd' for OpenBSD
os.type()
ऑपरेटिंग मोड नाम लौटाता है, जैसा कि POSIX सिस्टम पर uname द्वारा, या विंडोज़ पर ver कमांड द्वारा लौटाया जाता है।
const os = require('os');
// Get OS type
console.log(`OS Type: ${os.type()}`);
// Examples:
// - 'Linux' on Linux
// - 'Darwin' on macOS
// - 'Windows_NT' on Windows
os.release()
ऑपरेटिंग मोड रिलीज़ नंबर लौटाता है।
const os = require('os');
// Get OS release information
console.log(`OS Release: ${os.release()}`);
// Examples:
// - '10.0.19044' on Windows 10
// - '21.6.0' on macOS Monterey
// - '5.15.0-46-generic' on Ubuntu
os.version()
कर्नेल संस्करण की पहचान करने वाली एक स्ट्रिंग लौटाता है। विंडोज़ पर, इसमें कॉन्फ़िगरेशन जानकारी शामिल है।
const os = require('os');
// Get kernel version
console.log(`Kernel Version: ${os.version()}`);
// Example output:
// - Windows: 'Windows 10 Enterprise 10.0.19044'
// - Linux: '#49-Ubuntu SMP Tue Aug 2 08:49:28 UTC 2022'
// - macOS: 'Darwin Kernel Version 21.6.0: ...'
उपयोगकर्ता और पर्यावरण
os.userInfo()
वर्तमान में उपयोगकर्ता के बारे में उपयोगी जानकारी प्रदान करता है।
const os = require('os');
// Get current user information
const user = os.userInfo();
console.log('User Information:');
console.log(`- Username: ${user.username}`);
console.log(`- User ID: ${user.uid}`);
console.log(`- Group ID: ${user.gid}`);
console.log(`- Home Directory: ${user.homedir}`);
// On Windows, you can also get the user's domain
if (os.platform() === 'win32') {
console.log(`- Domain: ${user.domain || 'N/A'}`);
}
// Note: user.shell is only available on POSIX platforms
if (user.shell) {
console.log(`- Default Shell: ${user.shell}`);
}
os.homedir()
वर्तमान उपयोगकर्ता की होम निर्देशिका लौटाता है।
const os = require('os');
const path = require('path');
// Get the home directory
const homeDir = os.homedir();
console.log(`Home Directory: ${homeDir}`);
// Example: Create a path to a config file in the user's home directory
const configPath = path.join(homeDir, '.myapp', 'config.json');
console.log(`Config file will be saved to: ${configPath}`);
os.hostname()
निष्पादन योग्य का होस्टनाम लौटाता है।
const os = require('os');
// Get the system hostname
const hostname = os.hostname();
console.log(`Hostname: ${hostname}`);
// Example: Use hostname in logging or configuration
console.log(`Server started on ${hostname} at ${new Date().toISOString()}`);
os.tmpdir()
ऑपरेटिंग सिस्टम की डिफ़ॉल्ट अस्थायी फ़ाइलों के लिए एक निर्देशिका प्रदान करता है।
const os = require('os');
// Get the system default temp dir
console.log(`Temporary Directory: ${os.tmpdir()}`);
कंप्यूटर संसाधन
os.cpus()
प्रत्येक तार्किक सीपीयू कोर के बारे में जानकारी युक्त वस्तुओं की एक श्रृंखला प्रदान करता है।
const os = require('os');
// Get CPU information
const cpus = os.cpus();
console.log(`Number of CPU Cores: ${cpus.length}`);
// Display information about each CPU core
cpus.forEach((cpu, index) => {
console.log(`\nCPU Core ${index + 1}:`);
console.log(`- Model: ${cpu.model}`);
console.log(`- Speed: ${cpu.speed} MHz`);
console.log('- Times (ms):', {
user: cpu.times.user,
nice: cpu.times.nice,
sys: cpu.times.sys,
idle: cpu.times.idle,
irq: cpu.times.irq
});
});
सीपीयू उपयोग की गणना (उदाहरण के लिए, दो माप आवश्यक हैं)
// Calculate total CPU usage (example, requires two measurements)
function calculateCpuUsage(prevCpus) {
const currentCpus = os.cpus();
const usage = [];
for (let i = 0; i < currentCpus.length; i++) {
const current = currentCpus[i];
const prev = prevCpus ? prevCpus[i] : { times: { user: 0, nice: 0, sys: 0, idle: 0, irq: 0 } };
const prevIdle = prev.times.idle;
const idle = current.times.idle - prevIdle;
let total = 0;
for (const type in current.times) {
total += current.times[type] - (prev.times[type] || 0);
}
const usagePercent = ((1 - idle / total) * 100).toFixed(1);
usage.push(parseFloat(usagePercent));
}
return {
perCore: usage,
average: (usage.reduce((a, b) => a + b, 0) / usage.length).toFixed(1),
cpus: currentCpus
};
}
// Example usage of CPU usage calculation
console.log('\nCPU Usage (requires two measurements):');
const firstMeasure = os.cpus();
// Simulate some CPU work
for (let i = 0; i < 1000000000; i++) {}
const usage = calculateCpuUsage(firstMeasure);
console.log(`Average CPU Usage: ${usage.average}%`);
ओएस.टोटलमेम() और ओएस.फ्रीमेम()
विधि बाइट्स में कुल और मुक्त सिस्टम मेमोरी लौटाती है।
const os = require('os');
// Format bytes to human-readable format
function formatBytes(bytes, decimals = 2) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
// Get memory information
const totalMem = os.totalmem();
const freeMem = os.freemem();
const usedMem = totalMem - freeMem;
const usagePercent = ((usedMem / totalMem) * 100).toFixed(2);
console.log('Memory Information:');
console.log(`- Total Memory: ${formatBytes(totalMem)}`);
console.log(`- Free Memory: ${formatBytes(freeMem)} (${((freeMem / totalMem) * 100).toFixed(2)}%)`);
console.log(`- Used Memory: ${formatBytes(usedMem)} (${usagePercent}%)`);
// Example: Check if there's enough free memory
const MIN_FREE_MEMORY = 200 * 1024 * 1024; // 200MB
if (freeMem < MIN_FREE_MEMORY) {
console.warn('Warning: Low on memory!');
} else {
console.log('System has sufficient memory available');
}
os.loadavg()
1, 5, और 15 मिनट के औसत लोड के साथ एक सरणी लौटाता है।
const os = require('os');
// Get load averages
const loadAverages = os.loadavg();
console.log('System Load Averages (1, 5, 15 min):', loadAverages);
// On Linux/Unix, load average represents the average system load over the last 1, 5, and 15 minutes
// The values represent the number of processes in the system run queue
const [oneMin, fiveMin, fifteenMin] = loadAverages;
const cpuCount = os.cpus().length;
console.log(`1-minute load average: ${oneMin.toFixed(2)} (${(oneMin / cpuCount * 100).toFixed(1)}% of ${cpuCount} cores)`);
console.log(`5-minute load average: ${fiveMin.toFixed(2)}`);
console.log(`15-minute load average: ${fifteenMin.toFixed(2)}`);
// Example: Check if system is under heavy load
const isSystemOverloaded = oneMin > cpuCount * 1.5;
if (isSystemOverloaded) {
console.warn('Warning: System is under heavy load!');
} else {
console.log('System load is normal');
}
नेटवर्क जानकारी
os.networkInterfaces()
एक ऑब्जेक्ट लौटाता है जिसमें नेटवर्क इंटरफ़ेस होता है जिसके लिए एक नेटवर्क पता सौंपा गया है।
const os = require('os');
// Get network interfaces information
const networkInterfaces = os.networkInterfaces();
console.log('Network Interfaces:');
// Iterate over each network interface
Object.entries(networkInterfaces).forEach(([name, addresses]) => {
console.log(`\nInterface: ${name}`);
addresses.forEach((address) => {
console.log(`- Family: ${address.family}`);
console.log(` Address: ${address.address}`);
console.log(` Netmask: ${address.netmask}`);
console.log(` MAC: ${address.mac || 'N/A'}`);
console.log(` Internal: ${address.internal}`);
});
});
// Example: Find the first non-internal IPv4 address
function getLocalIpAddress() {
const interfaces = os.networkInterfaces();
for (const name of Object.keys(interfaces)) {
for (const iface of interfaces[name]) {
if (iface.family === 'IPv4' && !iface.internal) {
return iface.address;
}
}
}
return '127.0.0.1'; // Fallback to localhost
}
const localIp = getLocalIpAddress();
console.log(`\nLocal IP Address: ${localIp}`);
os.uptime()
सिस्टम चलने का समय सेकंड में लौटाता है।
const os = require('os');
// Get system uptime in seconds
const uptime = os.uptime();
console.log(`System Uptime: ${uptime} seconds`);
// Format uptime in a more readable way
const uptimeDays = Math.floor(uptime / (60 * 60 * 24));
const uptimeHours = Math.floor((uptime % (60 * 60 * 24)) / (60 * 60));
const uptimeMinutes = Math.floor((uptime % (60 * 60)) / 60);
const uptimeSeconds = Math.floor(uptime % 60);
console.log(`System has been running for: ${uptimeDays} days, ${uptimeHours} hours, ${uptimeMinutes} minutes, ${uptimeSeconds} seconds`);
ओएस स्थिरांक और उपयोगिताएँ
os.constants
आमतौर पर उपयोग की जाने वाली ऑपरेटिंग विधि किसी ऑब्जेक्ट को त्रुटि कोड, प्रक्रिया सिग्नल आदि के लिए विशिष्ट स्थिरांक के साथ लौटाती है।
const os = require('os');
// Get all signal constants
console.log('Signal Constants:', os.constants.signals);
// Example: Handle common signals
process.on('SIGINT', () => {
console.log('Received SIGINT. Performing cleanup...');
process.exit(0);
});
process.on('SIGTERM', () => {
console.log('Received SIGTERM. Shutting down gracefully...');
process.exit(0);
});
console.log('Process is running. Press Ctrl+C to exit.');
os.EOL
वर्तमान ऑपरेटिंग मोड के लिए एक लाइन-एंडिंग मार्कर लौटाता है।
const os = require('os');
const fs = require('fs');
// Get the end-of-line marker for the current OS
console.log('End of Line character:', JSON.stringify(os.EOL));
// Example: Write a file with platform-specific line endings
const lines = [
'First line',
'Second line',
'Third line'
];
// Join lines with the correct EOL character
const content = lines.join(os.EOL);
fs.writeFileSync('output.txt', content);
console.log('File written with platform-appropriate line endings');
सर्वोत्तम अभ्यास
1. गलियों का सही संचालन
क्रॉस-प्लेटफ़ॉर्म संगतता सुनिश्चित करने के लिए फ़ाइल पथों के लिए स्ट्रिंग संयोजन के बजाय हमेशा path.join() का उपयोग करें।
// Good
const filePath = path.join(os.homedir(), 'app', 'config.json');
// Bad (won't work on Windows)
const badPath = `${os.homedir()}/app/config.json`;
2. os.EOL से सावधान रहें
फ़ाइलें लिखते समय लाइन ब्रेक से सावधान रहें। क्रॉस-प्लेटफ़ॉर्म अनुकूलता के लिए os.EOL का उपयोग करें।
const content = `First Line${os.EOL}Second Line${os.EOL}Third Line`;
fs.writeFileSync('output.txt', content, 'utf8');
3. स्मृति बाधाओं को संभालना
मेमोरी गहन संचालन करने से पहले उपलब्ध मेमोरी की जाँच करें।
const MIN_FREE_MEMORY_MB = 500; // 500MB minimum free memory
function canPerformMemoryIntensiveOperation() {
const freeMemMB = os.freemem() / (1024 * 1024);
return freeMemMB > MIN_FREE_MEMORY_MB;
}
if (!canPerformMemoryIntensiveOperation()) {
console.warn('Not enough free memory to perform this operation');
// Handle the error appropriately
}
व्यावहारिक उदाहरण
सिस्टम सूचना डैशबोर्ड
यह उदाहरण एक विस्तृत सिस्टम सूचना रिपोर्ट तैयार करता है:
const os = require('os');
function getSystemInfo() {
const info = {
os: {
type: os.type(),
platform: os.platform(),
architecture: os.arch(),
release: os.release(),
hostname: os.hostname(),
uptime: formatUptime(os.uptime())
},
user: {
username: os.userInfo().username,
homedir: os.homedir(),
tempdir: os.tmpdir()
},
memory: {
total: formatBytes(os.totalmem()),
free: formatBytes(os.freemem()),
usage: `${((1 - os.freemem() / os.totalmem()) * 100).toFixed(2)}%`
},
cpu: {
model: os.cpus()[0].model,
cores: os.cpus().length,
speed: `${os.cpus()[0].speed} MHz`
}
};
return info;
}
function formatUptime(seconds) {
const days = Math.floor(seconds / (60 * 60 * 24));
const hours = Math.floor((seconds % (60 * 60 * 24)) / (60 * 60));
const minutes = Math.floor((seconds % (60 * 60)) / 60);
const secs = Math.floor(seconds % 60);
return `${days}d ${hours}h ${minutes}m ${secs}s`;
}
function formatBytes(bytes) {
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (bytes === 0) return '0 Bytes';
const i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
return `${(bytes / Math.pow(1024, i)).toFixed(2)} ${sizes[i]}`;
}
// Display the system information dashboard
const systemInfo = getSystemInfo();
console.log('======= SYSTEM INFORMATION DASHBOARD =======');
console.log(JSON.stringify(systemInfo, null, 2));
// Display in a more formatted way
console.log('\n======= FORMATTED SYSTEM INFORMATION =======');
console.log(`OS: ${systemInfo.os.type} (${systemInfo.os.platform} ${systemInfo.os.architecture})`);
console.log(`Version: ${systemInfo.os.release}`);
console.log(`Hostname: ${systemInfo.os.hostname}`);
console.log(`Uptime: ${systemInfo.os.uptime}`);
console.log(`User: ${systemInfo.user.username}`);
console.log(`Home Directory: ${systemInfo.user.homedir}`);
console.log(`CPU: ${systemInfo.cpu.model}`);
console.log(`Cores: ${systemInfo.cpu.cores}`);
console.log(`Speed: ${systemInfo.cpu.speed}`);
console.log(`Memory Total: ${systemInfo.memory.total}`);
console.log(`Memory Free: ${systemInfo.memory.free}`);
console.log(`Memory Usage: ${systemInfo.memory.usage}`);
संसाधन पर्यवेक्षक
यह उदाहरण एक बुनियादी संसाधन मॉनिटर बनाता है जो प्रति सेकंड एक बार अपडेट होता है:
const os = require('os');
function monitorResources() {
console.clear(); // Clear console for a cleaner display
const now = new Date().toLocaleTimeString();
console.log(`======= RESOURCE MONITOR (${now}) =======`);
// CPU Usage
const cpus = os.cpus();
console.log(`\nCPU Cores: ${cpus.length}`);
// Calculate CPU usage (this is approximate since we need two measurements)
const cpuUsage = cpus.map((cpu, index) => {
const total = Object.values(cpu.times).reduce((acc, tv) => acc + tv, 0);
const idle = cpu.times.idle;
const usage = ((total - idle) / total * 100).toFixed(1);
return `Core ${index}: ${usage}% used`;
});
console.log(cpuUsage.join('\n'));
// Memory Usage
const totalMem = os.totalmem();
const freeMem = os.freemem();
const usedMem = totalMem - freeMem;
console.log('\nMemory Usage:');
console.log(`Total: ${formatBytes(totalMem)}`);
console.log(`Used: ${formatBytes(usedMem)} (${(usedMem / totalMem * 100).toFixed(1)}%)`);
console.log(`Free: ${formatBytes(freeMem)} (${(freeMem / totalMem * 100).toFixed(1)}%)`);
// System Uptime
console.log(`\nSystem Uptime: ${formatUptime(os.uptime())}`);
// Process Info
console.log('\nProcess Information:');
console.log(`PID: ${process.pid}`);
console.log(`Memory Usage: ${formatBytes(process.memoryUsage().rss)}`);
console.log(`User: ${os.userInfo().username}`);
}
function formatBytes(bytes) {
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (bytes === 0) return '0 Bytes';
const i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
return `${(bytes / Math.pow(1024, i)).toFixed(2)} ${sizes[i]}`;
}
function formatUptime(seconds) {
const days = Math.floor(seconds / (60 * 60 * 24));
const hours = Math.floor((seconds % (60 * 60 * 24)) / (60 * 60));
const minutes = Math.floor((seconds % (60 * 60)) / 60);
const secs = Math.floor(seconds % 60);
return `${days}d ${hours}h ${minutes}m ${secs}s`;
}
// Initial display
monitorResources();
// Update every second (note: in a real application, you might not want
// to update this frequently as it uses CPU resources)
const intervalId = setInterval(monitorResources, 1000);
// In a real application, you would need to handle cleanup:
// clearInterval(intervalId);
// For this example, we'll run for 10 seconds then stop
console.log('Monitor will run for 10 seconds...');
setTimeout(() => {
clearInterval(intervalId);
console.log('\nResource monitoring stopped.');
}, 10000);
प्लेटफ़ॉर्म-विशिष्ट व्यवहार
यह उदाहरण दर्शाता है कि ऑपरेटिंग मोड के आधार पर अपने एप्लिकेशन के व्यवहार को कैसे समायोजित करें:
const os = require('os');
const fs = require('fs');
const path = require('path');
// Function to determine a good location for app data based on the OS
function getAppDataPath(appName) {
const platform = os.platform();
let appDataPath;
switch (platform) {
case 'win32': // Windows
appDataPath = path.join(process.env.APPDATA || '', appName);
break;
case 'darwin': // macOS
appDataPath = path.join(os.homedir(), 'Library', 'Application Support', appName);
break;
case 'linux': // Linux
appDataPath = path.join(os.homedir(), '.config', appName);
break;
default: // Fallback for other platforms
appDataPath = path.join(os.homedir(), `.${appName}`);
}
return appDataPath;
}
// Function to get appropriate command based on OS
function getOpenCommand() {
const platform = os.platform();
switch (platform) {
case 'win32': // Windows
return 'start';
case 'darwin': // macOS
return 'open';
default: // Linux and others
return 'xdg-open';
}
}
// Example usage
const appName = 'myapp';
const appDataPath = getAppDataPath(appName);
const openCommand = getOpenCommand();
console.log(`OS Platform: ${os.platform()}`);
console.log(`OS Type: ${os.type()}`);
console.log(`Recommended App Data Path: ${appDataPath}`);
console.log(`Open Command: ${openCommand}`);
// Example of platform-specific behavior
console.log('\nPlatform-Specific Actions:');
if (os.platform() === 'win32') {
console.log('- Using Windows-specific registry functions');
console.log('- Setting up Windows service');
} else if (os.platform() === 'darwin') {
console.log('- Using macOS keychain for secure storage');
console.log('- Setting up launchd agent');
} else if (os.platform() === 'linux') {
console.log('- Using Linux systemd for service management');
console.log('- Setting up dbus integration');
}
// Example of checking for available memory and adjusting behavior
const availableMemGB = os.freemem() / (1024 * 1024 * 1024);
console.log(`\nAvailable Memory: ${availableMemGB.toFixed(2)} GB`);
if (availableMemGB < 0.5) {
console.log('Low memory mode activated: reducing cache size and disabling features');
} else if (availableMemGB > 4) {
console.log('High memory mode activated: increasing cache size and enabling all features');
} else {
console.log('Standard memory mode activated: using default settings');
}
// Example of CPU core detection for parallel processing
const cpuCount = os.cpus().length;
console.log(`\nCPU Cores: ${cpuCount}`);
const recommendedWorkers = Math.max(1, cpuCount - 1); // Leave one core for the system
console.log(`Recommended worker processes: ${recommendedWorkers}`);
सारांश
Node.js OS .
इसके साथ, आप यह कर सकते हैं:
ये कौशल विशेष रूप से उपयोगी हैं:
क्रॉस-प्लेटफ़ॉर्म अनुप्रयोग
मेजबान वातावरण के अनुकूल
कंप्यूटर संसाधनों की निगरानी करना
प्रदर्शन और संसाधन उपयोग की निगरानी करना
निदान उपकरण
निदान उपकरणों का विकास
OS मॉड्यूल का उपयोग करके, आप अपने Node.js अनुप्रयोगों को अधिक मजबूत, कुशल और विभिन्न ऑपरेटिंग वातावरणों के अनुकूल बना सकते हैं।
अभ्यास
उपयुक्त मॉड्यूल को खींचें और छोड़ें जो ऑपरेटिंग मोड से संबंधित एप्लिकेशन विधियों और गुणों को प्रदान करता है।
The ______ module.