Reputation: 323
How to grep the wanted text and receive it into stdout as JSON, i hope that someone can answer that , the result i get in the server API is text with. But I want the result to be in JSON {}, so I can loop through it in front-end. This is my back-end requests
var express = require('express');
var exec = require("child_process").exec;
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || xxxx;
app.get('/', function(req, res) {
res.json('API is Online!');
});
app.post('/data', function(req, res){
//executes my shell script - test.sh when a request is posted to the server
exec('sh test.sh' , function (err, stdout, stderr) {
if (!err) {
res.json({'results': stdout})
}
});
})
app.listen(port);
console.log('Listening on port ' + port);
This is the code that runs in bash
#!/bin/bash
free -m
thanks for https://stackoverflow.com/users/2076949/darklightcode i can split the results but can i get inside the array the results like this
{ results : [ { "total" : the total number, "free" : the free number, "etc" : "etc" } ] }
not like this
{
"results": [
" total used free shared buff/cache available",
"Mem: 992 221 235 16 534 590",
"Swap: 263 245 18",
""
] }
Upvotes: 4
Views: 7178
Reputation: 2772
Split the output by line.
res.json({'results': stdout.split('\n')})
- now you can loop through results
.
PS: The last line feed can be removed because it's empty. It's a new line after the script is done.
UPDATE
See the function below and use it like convertFreeMemory(stdout.split('\n'))
console.clear();
let data = {
"results": [
" total used free shared buff/cache available",
"Mem: 992 221 235 16 534 590",
"Swap: 263 245 18",
""
]
};
convertFreeMemory = (input) => {
let objectFormat = [];
input = input
.filter(i => i.length)
.map((i, idx) => {
i = i.split(' ').filter(x => x.length);
if (idx !== 0) {
i.splice(0, 1);
}
return i;
});
let [header, ...data] = input;
for (let idx = 0; idx < data.length; idx++) {
let newObj = {};
for (let index = 0; index < header.length; index++) {
if (typeof newObj[header[index]] === 'undefined') {
newObj[header[index]] = '';
}
let value = data[idx][index];
newObj[header[index]] = typeof value === 'undefined' ? '' : value;
}
objectFormat.push(newObj);
}
return objectFormat;
}
console.log(convertFreeMemory(data.results));
Upvotes: 2