项目使用nodejs写服务端,有个功能就是统计代理服务器流量,然后把统计的数据通过echarts渲染到页面。
当然统计数据这里用到了 定时器,在使用的是
schedule.scheduleJob('*/15 * * * * * ', function () {
console.log('timer !!!!!!!!!!');
var dataObj1 = {};
iplists.forEach(function (ele, index) {
var req = http.request("http://" + ele + ":14567/stat", function (res) {
dataObj1.time = new Date(res.headers.date);
dataObj1.ip = req.getHeader("host").split(":")[0];
res.setEncoding('utf-8');
var tempData = '';
res.on('data', function (chunk) {
tempData += chunk;
var resultObj = JSON.parse(tempData);
dataObj1.flow = resultObj.bw15s;
var flow1 = new flowrank1({
ip: dataObj1.ip,
flow: dataObj1.flow,
time: new Date(dataObj1.time)
});
flow1.save(function (err, flow1) {
if (err) {
console.log(err);
return;
}
});
});
});
req.on("error", function (err) {
console.log(err);
});
req.end()
});
});
现在来展示 需要根据前端传过来的 时间戳 来筛选出数据的代码,处理时间我用到了moment这个类库,基本包含了时间所有的处理方法。
总结以下moment的几个常用的函数:
moment().startOf('year'); // set to January 1st, 12:00 am this year
moment().startOf('month'); // set to the first of this month, 12:00 am
moment().startOf('quarter'); // set to the beginning of the current quarter, 1st day of months, 12:00 am
moment().startOf('week'); // set to the first day of this week, 12:00 am
moment().startOf('isoWeek'); // set to the first day of this week according to ISO 8601, 12:00 am
moment().startOf('day'); // set to 12:00 am today
moment().startOf('date'); // set to 12:00 am today
moment().startOf('hour'); // set to now, but with 0 mins, 0 secs, and 0 ms
moment().startOf('minute'); // set to now, but with 0 seconds and 0 milliseconds
moment().startOf('second'); // same as moment().milliseconds(0);
moment().diff(Moment|String|Number|Date|Array);
moment().diff(Moment|String|Number|Date|Array, String);
moment().diff(Moment|String|Number|Date|Array, String, Boolean);
var a = moment([2008, 9]);
var b = moment([2007, 0]);
a.diff(b, 'years'); // 1
a.diff(b, 'years', true); // 1.75
moment().add(Number, String);
moment().add(Duration);
moment().add(Object);