DEV Community

Amin
Amin

Posted on

Get your battery capacity in Linux with Node

Getting your battery capacity in GNU/Linux is pretty simple since it does not rely on any third-party libraries or programs. You can just read it directly from a file. Using Node, this operation gets very trivial and can be as simple as below.

$ touch index.js
Enter fullscreen mode Exit fullscreen mode
const {promises: {readFile}} = require("fs");

const append =
  newString =>
    string =>
      `${string}${newString}`;

const trim =
  string =>
    string.trim();

const main = async () => {
  const capacity =
    "/sys/class/power_supply/BAT0/capacity";

  const battery =
    await readFile(capacity)
      .then(String)
      .then(trim)
      .then(append("%"))
      .catch(() => "No battery");

  console.log(battery);
};

main();
Enter fullscreen mode Exit fullscreen mode
$ node index.js
34%
Enter fullscreen mode Exit fullscreen mode

Top comments (0)