Skip to content
Advertisement

How do I extract data from df ~ onto my website?

I am creating a pie chart which shows how much disk space is available/used on my linux box. However, I am unsure how to parse the data onto a microservice url. Help will greatly be appreciated.

Here is what I have at the moment:

Router:

router.route('/linux_disk').get(disk.get_linux_disk)

Controller:

 function get_linux_disk(req, res, next) {
  try {
    var cmd = `df ~`;
    exec(cmd)

    rows = [];
    rows.push({"Command": cmd});
    if (rows.length >= 1) {
      res.status(200).json(rows);
    } else {
      res.status(404).end();
    }
  } catch (err) {
    next(err);
  }
}

Advertisement

Answer

You might try the approach below, we create a row object for each entry that the df command creates. Once you have this you should be able to create your pie chart from this:

const { exec } = require('child_process');
const { promisify } = require('util');
const execPromise = promisify(exec);

async function get_linux_disk(req, res, next) {
    try {
        const result = await execPromise(`df ~`)
        const lines = result.stdout.split("n");
        const keys = lines[0].split(/s+/ig);
        // Skip the header row when assigning objects..
        const rows = lines.slice(1).map(line => {
            // Parse each line..
            const values = line.split(/s+/ig);
            return keys.reduce((o, k, index) => {
                o[k] = values[index];
                return o;
            }, {})
        });
        res.status(200).json(rows);
    } catch (err) {
        res.status(500).send(err.message);
    }
}

The resulting JSON will look a bit like so :

[
    {
        "Filesystem": "/dev/sda1",
        "1K-blocks": "10253588",
        "Used": "7971516",
        "Available": "1741504",
        "Use%": "83%",
        "Mounted": "/"
    }
]
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement