Giter Club home page Giter Club logo

node-os-utils's Introduction

Description

monitor vital signs of your server :

  • CPU average usage
  • Free and used drive space
  • Free and used memory space
  • Operating System
  • All processes running
  • TTY/SSH opened
  • Total opened files
  • Network speed (input and output)

node-os-utils

JavaScript Style Guide Build Status NPM Version NPM Downloads

An operating system utility library. Some methods are wrappers of node libraries and others are calculations made by the module.

os-utils extended

Installation

One line installation with npm.

$ npm install node-os-utils --save

Then in your code

Example

var osu = require('node-os-utils')
var cpu = osu.cpu

var count = cpu.count() // 8

cpu.usage()
  .then(cpuPercentage => {
    console.log(cpuPercentage) // 10.38
  })

var osCmd = osu.osCmd

osCmd.whoami()
  .then(userName => {
    console.log(userName) // admin
  })

Configuration

require('node-os-utils').options

Default settings:

  • NOT_SUPPORTED_VALUE is not supported. os not supported, return value.
  • INTERVAL is 1000 millisecond. Represents the refresh of the cpu and network workers.

⚠️ If this module uses too much CPU, set the INTERVAL value to 10000 or more.

Info

If you have not supported in some categories, your OS configuration is not supported for this option.

You can use require('node-os-utils').isNotSupported() to decide not supported.

var osu = require('node-os-utils')
var osCmd = osu.osCmd

osCmd
  .topCpu()
  .then(function(res){
    if(osu.isNotSupported(res)){
      // Handle 'not supported'
    }else{
      // Things to do...
    }
  })

Usage

The following methods are available:

require('node-os-utils').cpu

cpu.average():object

CPU average

var osu = require('node-os-utils')
var cpu = osu.cpu

var info = cpu.average()

console.log(info)
{ totalIdle: 33526410,
  totalTick: 37460330,
  avgIdle: 4190801.25,
  avgTotal: 4682541.25 }

cpu.usage(interval):Promise(number)

CPU average usage

  • [interval]: number - interval millisecond. defaulta: 1000
var osu = require('node-os-utils')
var cpu = osu.cpu

cpu.usage()
  .then(info => {
    console.log(info)
  })
10.06

cpu.free(interval):Promise(number)

cpu free percentage

  • [interval]: number - interval millisecond. defaulta: 1000
var osu = require('node-os-utils')
var cpu = osu.cpu

cpu.free()
  .then(info => {
    console.log(info)
  })
89.26

cpu.count():number

cpu.model():string

cpu.loadavg():Array[number]

cpu.loadavgTime(time):number

  • time: number - 1, 5 or 15 minutes, defaulta: 1

require('node-os-utils').drive

drive.info():Promise(Object)

drive info

var osu = require('node-os-utils')
var drive = osu.drive

drive.info()
  .then(info => {
    console.log(info)
  })
{ totalGb: '464.8',
  usedGb: '147.7',
  freeGb: '316.9',
  usedPercentage: '31.8',
  freePercentage: '68.2' }

drive.free():Promise(Object)

{ totalGb: '464.8', freeGb: '316.9', freePercentage: '68.2' }

drive.used():Promise(Object)

{ totalGb: '464.8', usedGb: '316.9', usedPercentage: '68.2' }

require('node-os-utils').mem

mem.info():Promise(Object)

memory info

var osu = require('node-os-utils')
var mem = osu.mem

mem.info()
  .then(info => {
    console.log(info)
  })
{ totalMemMb: 16384,
  usedMemMb: 13403.41,
  freeMemMb: 2980.59,
  freeMemPercentage: 18.19 }

mem.free():Promise(Object)

{ totalMemMb: 16384, freeMemMb: 3033.63 }

mem.used():Promise(Object)

{ totalMemMb: 16384, usedMemMb: 13421.15 }

mem.totalMem():number

17179869184

require('node-os-utils').netstat

netstat.stats():Promise(Array[Object])

var osu = require('node-os-utils')
var netstat = osu.netstat

netstat.stats()
  .then(info => {
    console.log(info)
  })
[ { interface: 'lo',
    inputBytes: '731508412',
    outputBytes: '731508412' },
  { interface: 'eth0',
    inputBytes: '1356471479',
    outputBytes: '26631036763' } ]

netstat.inOut(interval):Promise(Object)

  • [interval]: number - interval millisecond. defaulta: 1000
var osu = require('node-os-utils')
var netstat = osu.netstat

netstat.inOut()
  .then(info => {
    console.log(info)
  })
{ total: { inputMb: 0.02, outputMb: 1.22 },
  eth0: { inputMb: 0.02, outputMb: 1.22 } }

require('node-os-utils').openfiles

openfiles.openFd():Promise(number)

Total opened files

1088

require('node-os-utils').os

os.oos():Promise(string)

original operating system

Mac OS X 10.12.5
Red Hat 7.3

os.platform():string

os.uptime():number - (seconds)

os.ip():string

os.hostname():string

os.type():string

os.arch():string


require('node-os-utils').proc

proc.totalProcesses():Promise(number)

proc.zombieProcesses():Promise(number)


require('node-os-utils').users

users.openedCount():Promise(number)

TTY/SSH opened


require('node-os-utils').osCmd

osCmd.topCpu():Promise(string)

osCmd.topMem():Promise(string)

osCmd.vmstats():Promise(string)

......

var bucket = require('./bucket')
var exec = require('./exec')
var wrapExec = exec.wrapExec

bucket.osCmd = {
  topCpu: wrapExec('ps -eo pcpu,user,args --no-headers | sort -k 1 -n | tail -n 10 | sort -k 1 -nr | cut -c 1-70'),
  topMem: wrapExec('ps -eo pmem,pid,cmd | sort -k 1 -n | tail -n 10 | sort -k 1 -nr | cut -c 1-70'),
  vmstats: wrapExec('vmstat -S m'),
  processesUsers: wrapExec('ps hax -o user | sort | uniq -c'),
  diskUsage: wrapExec('df -h'),
  who: wrapExec('who'),
  whoami: wrapExec('whoami'),
  openPorts: wrapExec('lsof -Pni4 | grep ESTABLISHED'),
  ifconfig: wrapExec('ifconfig')
}

License

MIT. Copyright (c).

node-os-utils's People

Contributors

andreasbrett avatar chaos-zhu avatar dependabot[bot] avatar halitcolak avatar jimmyliao11 avatar kylefarris avatar sabattle avatar sunilwang avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

node-os-utils's Issues

drive info shows wrong data on MacBook Air M1

As described in the title this package shows a wrong count for total of capacity (128 not 256), wrong data for used (14.3 not 117.97).

Used on Apple MacBook Air M1 2020
Used with Electron 15.3.0

osu.mem.info() totalMemMb is actually MiB

The function from the title is called .totalMemMb, which suggests a return value in megabit.
I found the actual return value to be in MiB, (mebibytes)
(Mb = megabit, MB = megabyte, MiB = mebibyte, there's a difference!)

Therefore I think the function name should be changed to .totalMemMib.

osu.drive failing

Hi,

I have an issue with drive.anything failing. I am getting the disk name invalid and / not found. I found on the net that you have fixed this before however there is another issue going on here. I have this problem going on with my ubuntu server. "df: /run/user/1000/doc: Operation not permitted"

You can read about it here: https://bugs.launchpad.net/ubuntu/+source/xdg-desktop-portal/+bug/1905623 Pardon me if you don't like links posted. My work around was to build the command line and pass it to exec.

let command = df -kP + diskName; then pass the drive I want as a parameter to the drive object. Then pass the command to your exec function. After that df only returns information about that particular mount with the correct header and all works fine. I cannot however run df without that error popping up.

Other than that, love what I have used so far. Thanks for the work!

Chris

空闲内存计算错误

freeMem = parseInt(resultMemory[1], 10) + (parseInt(resultMemory[3], 10) + parseInt(resultMemory[4], 10)) * 1024

应该是:

freeMem = (parseInt(resultMemory[1], 10) + parseInt(resultMemory[3], 10) + parseInt(resultMemory[4], 10)) * 1024

括号不对,导致计算有误

os.ip() throws error on linux without eth0

console.log(os.platform(), os.networkInterfaces());

linux {
  lo: [
    {
      address: '127.0.0.1',
      netmask: '255.0.0.0',
      family: 'IPv4',
      mac: '00:00:00:00:00:00',
      internal: true,
      cidr: '127.0.0.1/8'
    }
  ],
  ens160: [
    {
      address: '192.168.1.100',
      netmask: '255.255.255.0',
      family: 'IPv4',
      mac: '00:aa:bb:cc:dd:ff',
      internal: false,
      cidr: '192.168.1.100/24'
    }
  ]
}

Multiple drives?

Does this support multiple drives? If not, is it possible to add it somehow? :)

osu.drive dont works on Windows

My english is so bad, so I may sound incoherent or rude. So I'll get right to the point. i see in the in drive.js you are using df -kP. its a great commant for linux users (and servers) but when you try to run that on Windows console and the spam are inevitable
image

I check on forums and test by myself and i found the "equivalent" of df -kP and is get-psdrive –psprovider filesystem. Actually the command give you the Free Mem, Used Mem and Root, (not root or Administrator permission required)

well its posible to get compatibilty. just add a conditional for windows like this (or someting like this)

info: function (diskName) {
if (!diskName) {
diskName = '/'
}
return exec('df -kP').then(function (out) {

//required 'os' dependency
  info: function (diskName) {
    if (!diskName) {
      diskName = '/'
    }
    if (os.version().toLowerCase().includes('windows')) return exec('get-psdrive –psprovider filesystem', (out) => {})
    else (os.version().toLowerCase().includes('linux')) return exec('df -kP', (out) => {}) {}

i hope you have planed to add windows support on osu.drive. is very strange found good libraries with this feature.

executing df command in drive.info()

I really enjoy your npm pagage node-os-utils, but I ran into some problems using osu.drive functions. It kept throwing Error: disk name invalid and / not found.
So I did some debugging and found out, that you are using the df -kP command, to gather plain text information about free disk space.
After that you parse that information by using the headline column names and iterating through the rows looking for lines[i]['Mounted on'] === diskName. But this works only if the shell is running in english and df prints out an english headline. Which sadly isn't the case with me (it's german):
Screenshot 2019.12.24 22:34:48

For international support I whould like to suggest two possible fixes / updates:

  1. Changing line 43 of /lib/drive.js to
    return exec('LC_ALL="en_US.UTF-8";LANG="en_US.UTF-8";LANGUAGE="en_US:en";df -kP')().then(function(out) {

which whould set the language of the child process to english, so you can expect df to output a english headline.

  1. Changing line 12 of /lib/exec.js to
      cp.exec('LC_ALL="en_US.UTF-8";LANG="en_US.UTF-8";LANGUAGE="en_US:en";'+command, { shell: true }, function (err, stdout, stderr) {

which whould set the language of all child processes to english, so you can expect all command outputs to be english as well.

Merry Christmas from
Niklas Englert in Germany

(sorry for bad english)

Run Time error.

Hello, I am getting run time error ,The error is

`
/home/localhost/scrap/node_modules/node-os-utils/index.js:1
export let cpu = undefined;
^^^^^^

SyntaxError: Unexpected token 'export'
at wrapSafe (node:internal/modules/cjs/loader:1024:16)
at Module._compile (node:internal/modules/cjs/loader:1072:27)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10)
at Module.load (node:internal/modules/cjs/loader:973:32)
at Function.Module._load (node:internal/modules/cjs/loader:813:14)
at Module.require (node:internal/modules/cjs/loader:997:19)
at require (node:internal/modules/cjs/helpers:92:18)
at Object. (/home/masum/localhost/scrap/controller/OS/index.js:1:13)
at Module._compile (node:internal/modules/cjs/loader:1108:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10)
`

Exclude IOWAIT from CPU stats

Ref: https://git.joinfirefish.org/firefish/firefish/-/issues/10755

From our issue tracker:

What feature would you like implemented? (Please give us a brief description of what you'd like.)

Excluding IOWAIT from the CPU usage widget.

Why should we add this feature? (Please give us a brief description of why your feature is important.)

Counting IOWAIT in CPU usage can give an inaccurate representation of actual CPU load, since the CPU is idle during IOWAIT and can still process other things.

CPU Utilization not properly reported in K8s env

My application is containerized and runs in a K8S pod, here is the snippet:

var osu = require('node-os-utils')
var cpu = osu.cpu

let cpuUtilization: number = -1;

setInterval(async function () {
  cpu.usage()
    .then((cpuPercentage: number) => {
      cpuUtilization = cpuPercentage;
      logger.info(`Updating cpu utilization to cpuUtil=${cpuUtilization}`);
    });
}, 10 * 1000); // invoke every 10 seconds

Unfortunately, the library doesn't return correct value for POD utilization, the values never go over 35%, whereas on grafana dashboard Pods CPU utilization is reported to reach 100% with the CPU throttling taking place.

Is this a known issue?

[Bug] Wrong memory stats

I am running Homepage app (that uses this library) on Asus Tinker Board (armv7) and dietpi OS, and resources widget is showing wrong value for free memory (total is good but it's showing same value for free).
image

Devs of Homepage told me to open issue here.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.