Skip to content

Instantly share code, notes, and snippets.

@cgcai
Created June 19, 2013 08:40
Show Gist options
  • Select an option

  • Save cgcai/5812707 to your computer and use it in GitHub Desktop.

Select an option

Save cgcai/5812707 to your computer and use it in GitHub Desktop.
A quick hack to parse NEA Website for latest PSI figures using vanilla nodejs (without plugins). Written 19 June 2013 while choking on Indonesian haze and waiting for code to compile. --Xofel.
/* File: psi.js
A quick hack to parse NEA Website for latest PSI figures using vanilla nodejs (without plugins).
Written 19 June 2013 while choking on Indonesian haze and waiting for code to compile. --Xofel.
*/
var http = require("http");
var util = require("util");
var isNumber = function (n) {
return !isNaN(parseFloat(n)) && isFinite(n);
};
var padTime = function (s) {
while (s.length != 4) {
s += "0";
}
return s;
};
var html = ""
var request = http.get("http://app2.nea.gov.sg/anti-pollution-radiation-protection/air-pollution/psi/psi-and-pm2-5-readings", function (res) {
res.setEncoding("utf8");
res.on("data", function (chunk) {
html += chunk;
});
res.on("end", function () {
// Extract the <table> tag containing the data we want.
var tableStart = html.indexOf("<table");
var tableStartTagEnd = html.indexOf(">", tableStart);
var tableEnd = html.indexOf("</table>", tableStart);
var psiTable = html.substring(tableStartTagEnd + 1, tableEnd).trim();
var dataStart = psiTable.indexOf("</thead>") + 8;
var data = psiTable.substring(dataStart).trim();
var psiValues = new Array();
var valueIndex = 0;
var lastNumeric = 0;
var samples = 0;
var sum = 0;
var max = 0;
var min = 1000; // If it can get higher than this we're fucked anyway.
for (var i = 0 ; i < 4; i++) {
var rowEnd = data.indexOf("</tr>");
if (i % 2 != 0) {
var rowBegin = data.indexOf(">");
var row = data.substring(rowBegin + 1, rowEnd).trim();
for (var j = 0; j < 13; j++) {
var colEnd = row.indexOf("</td>");
if (j != 0) {
var colBegin = row.indexOf(">");
var col = row.substring(colBegin + 1, colEnd).trim();
if (isNumber(col)) {
lastNumeric = valueIndex;
// Statistics.
val = parseFloat(col);
samples++;
sum += val;
if (val > max) max = val;
if (val < min) min = val;
}
psiValues[valueIndex++] = col;
}
row = row.substring(colEnd + 5).trim();
}
}
data = data.substring(rowEnd + 5).trim();
}
console.log("The latest PSI is " + psiValues[lastNumeric] + " measured at " + padTime(lastNumeric) + "hrs.");
console.log("Mean PSI: " + (sum / samples) + " (" + samples + " samples)");
console.log("Max PSI: " + max);
console.log("Min PSI: " + min);
console.log("Source: National Environment Agency (www.nea.gov.sg)");
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment