I'm using Raspberry Pi with nodeJS
to do child_process.
On shell command, I do:
df -h
and the output is:
Sistem Berkas Besar Isi Sisa Isi% Dipasang di
/dev/root 58G 5,1G 50G 10% /
devtmpfs 460M 0 460M 0% /dev
tmpfs 464M 8,3M 456M 2% /dev/shm
tmpfs 464M 13M 452M 3% /run
tmpfs 5,0M 4,0K 5,0M 1% /run/lock
tmpfs 464M 0 464M 0% /sys/fs/cgroup
/dev/mmcblk0p1 44M 23M 22M 51% /boot
tmpfs 93M 0 93M 0% /run/user/1000
/dev/sda1 7,5G 2,0G 5,6G 27% /media/pi/USB DISK
Then now I do on nodeJS
script.
var exec = require('child_process').exec;
function execute(command, callback) {
var cmd = exec(command, function(error, stdout, stderr) {
console.log("error: " + error);
callback(stdout);
});
}
exec('df -h',(error,stdout,stderr) => {
if(error){
console.error( `exec error: ${error}` );
return;
}
var abc = [];
abc = stdout;
res.json(abc);
});
My question, how can I get specific of the output? Example I just want to get at row 1, it's 50G
stdout
is a string, so you can split it and then you can grab whichever rows you want. Example:
const { exec } = require('child_process')
exec('df -h', (error, stdout) => {
if (error) {
console.error(`exec error: ${error}`)
return
}
// split stdout on newlines, and filter to remove the ending empty string
const lines = stdout.split('\n').filter(Boolean)
// entry 0 will be the headers, we want the first non-header line
console.log(lines[1])
})
If you want to make that dynamic, you can use a function:
const getRowForDevice = (rows, device) =>
rows.filter((x) => x.startsWith(device))[0]
// rest of exec callback
console.log(getRowForDevice(lines, '/dev/root'))
Since the size is the second column, you can get just the size with another split and filter:
const lineWeWant = lines[0] // or try the function above
// split the string again, filter out empty strings, and then take the second entry
const sizeForDevice = lineWeWant.split(' ').filter(Boolean)[1]
And as a sidenote there's also this excellent package which might be easier than dealing with df
and child_process
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.