-
-
Save acfatah/ac47ac6abb52073c0230c786a5a68056 to your computer and use it in GitHub Desktop.
get battery info with node.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const http = require('http'); | |
const PORT = Number(process.argv[2]) || 8080; | |
const child_process = require('child_process'); | |
const Routes = { | |
BATTERY: /\/battery\/?/ | |
}; | |
const Status = { | |
NOT_FOUND: 404, | |
NOT_FOUND_MSG: '404 - Resource Not found', | |
OK: 200, | |
OK_MSG: '200 - Success', | |
BATTERY_ERROR: 500, | |
BATTERY_ERROR_MSG: '500 - Battery Error' | |
}; | |
const renderResult = (response, data) => { | |
response.writeHead(data.status, {'Content-Type': 'application/json'}); | |
response.write(JSON.stringify(data)); | |
response.end(); | |
}; | |
const switchConfigForCurrentOS = () => { | |
switch (process.platform) { | |
case 'linux': | |
return { | |
command: 'upower -i /org/freedesktop/UPower/devices/battery_BAT0 | grep -E "state|time to empty|to full|percentage"', | |
}; | |
case 'darwin': | |
//MAC | |
return { | |
command: 'pmset -g batt | egrep "([0-9]+\%).*" -o', | |
}; | |
case 'win32': | |
return { | |
command: 'WMIC Path Win32_Battery', | |
}; | |
default: | |
return { | |
command: '', | |
}; | |
} | |
}; | |
const getBatteryStatus = (response, config) => { | |
child_process.exec(config.command, (err, stdout, stderr) => { | |
if (err) { | |
console.error('child_process failed with error code: ' + err.code); | |
renderResult(response, { | |
status: Status.BATTERY_ERROR, | |
message: stderr | |
}); | |
} else { | |
try { | |
renderResult(response, { | |
status: Status.OK, | |
data: stdout | |
}); | |
} catch (e) { | |
console.error(e); | |
renderResult(response, { | |
status: Status.BATTERY_ERROR, | |
message: Status.BATTERY_ERROR_MSG | |
}); | |
} | |
} | |
}); | |
}; | |
const server = http.createServer((request, response) => { | |
const requestUrl = request.url; | |
const config = switchConfigForCurrentOS(); | |
if (Routes.BATTERY.test(requestUrl)) { | |
getBatteryStatus(response, config); | |
console.log('--- ', requestUrl); | |
} else { | |
renderResult(response, { | |
status: Status.NOT_FOUND, | |
message: Status.NOT_FOUND_MSG | |
}); | |
} | |
}).listen(PORT); | |
console.log('Server running on port ' + PORT); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment