-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
37 lines (31 loc) · 957 Bytes
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
const fs = require('fs');
const http = require('http');
const path = require('path');
const rpio = require('rpio');
const pin = 12;
rpio.open(pin, rpio.INPUT);
function handleAPI(request, response) {
const isLightOn = rpio.read(pin) == 0;
response.writeHead(200, { 'Content-Type': 'application/json' });
response.end(JSON.stringify({isLightOn}));
}
function handleClient(request, response) {
const file = path.join(__dirname, 'client/index.html');
fs.readFile(file, (err, content) => {
response.writeHead(200, { 'Content-Type': 'text/html' });
response.end(content, 'utf-8');
});
}
function handleRequest(request, response) {
if(request.url.match(/^\/api/)) {
handleAPI(request, response);
}
else {
handleClient(request, response);
}
}
const port = 8080;
http.createServer(handleRequest)
.listen(port, () => {
console.log(`Server started on port ${port}.`);
});