const child_process = require('child_process');
const os = require('os');
const getTopMemoryApps = () => {
return new Promise((resolve, reject) => {
child_process.exec('ps aux | sort -rk 4', (error, stdout, stderr) => {
if (error) {
reject(stderr)
} else {
const lines = stdout.trim().split('\n');
const data = lines.slice(0, 10).map(line => {
const columns = line.split(/\s+/);
return {
user: columns[0],
pid: columns[1],
cpu: columns[2],
mem: columns[3],
command: columns.slice(10).join(' '),
};
});
resolve(data);
}
});
});
};
const printTopMemoryApps = async () => {
const totalMemInGB = (os.totalmem() / (1024 * 1024 * 1024)).toFixed(2); // Convert to MB and round to two decimal places
const freeMemInGB = (os.freemem() / (1024 * 1024 * 1024)).toFixed(2); // Convert to GB and round to two decimal places
const usedMemInGB = (totalMemInGB - freeMemInGB).toFixed(2);
try {
const data = await getTopMemoryApps();
console.log(`Total memory: ${totalMemInGB} BG`);
console.log(`Used memory: ${usedMemInGB} BG`);
data.forEach(item => {
console.log(`\n PID: ${item.pid}, User: ${item.user}, Usage: ${item.mem}% - ${item.command}`);
});
} catch (err) {
console.error(err);
}
};
printTopMemoryApps();
解析
这段 Node.js 代码首先定义一个 getTopMemoryApps 函数,这个函数创建一个 Promise 来异步执行 ps aux | sort -rk 4 这个 shell 命令,这个命令可以列出内存使用量从高到低的进程。然后, printTopMemoryApps 函数将使用 os.totalmem 和 os.freemem 来获取总内存和已用内存,并打印出内存使用量最高的前 10 个进程。
ps aux: 这是一个 Unix 命令,用于列出当前运行的所有进程及其详细信息。
- a 表示列出终端上运行的所有进程,包含其他用户的进程。
- u 表示以用户为主的格式来显示进程状态。
- x 表示除了由终端启动的进程以外,也列出其他所有进程。
sort -rk 4: sort 是一个 Unix 命令,用于将输入的行进行排序。
- -r 选项意味着进行反向排序,也就是从大到小。
- -k 4 表示按照每行的第 4 列进行排序。
| 符号是 Unix 命令行的一个强大工具,称为管道 (pipe)。它把左边命令(在这里是 ps aux)的标准输出作为右边命令(在这里是 sort -rk 4)的标准输入。因此,ps aux | sort -rk 4 的含义是:执行 ps aux 命令,然后把其结果按照每行的第 4 列从大到小排序。
这些代码也同样仅能在 Unix 及 Unix-like 系统(如 Linux 和 MacOS)上运行。它同样可能会根据你的系统具体设置有所不同。