Nodejs简易设备信息面板
用于简单演示JS的AJAX,使用Nodejs做服务端。
1.服务端源码(与这篇文章一样)
var http = require('http');//引用模块
var os = require('os');
var netdev = "wlan0";//网卡名
http.createServer(function (req, res) {
var net = os.networkInterfaces();
res.writeHead(200, {'Content-Type': 'application/json'});//Http响应头
res.write("["+JSON.stringify({//生成json数据
hostname:os.hostname(),
platform:os.arch()+"-"+os.platform()+os.release(),
uptime:os.uptime().toFixed(0),//系统运行时间取整
load:os.loadavg(),
totalram:(os.totalmem()/1024).toFixed(0),
freeram:(os.freemem()/1024).toFixed(0),
}));
//网卡信息
res.end(","+JSON.stringify({//生成json数据
address:net[netdev][0]["address"],
family:net[netdev][0]["family"],
internal:net[netdev][0]["internal"]
})+"]");
}).listen(80);//监听端口
console.log('Server running at http://192.168.3.184');
2.HTML
源码
<script>
function getinfo(){
http=new XMLHttpRequest(); //AJAX
http.onreadystatechange=function() {
if (http.readyState==4){
if(http.status==200){
var info = JSON.parse(http.responseText); //转换为JSON对象
document.getElementById("ram").innerHTML=(info['freeram']/1024).toFixed(0)+'\/'+(info['totalram']/1024).toFixed(0)+"MB";
document.getElementById("time").innerHTML=(info["uptime"]/60).toFixed(2)+'min';
setInterval(function(){getinfo();},1500); //定时刷新(1.5s)
}}}
http.open("GET","/get",true); //连接
http.send(null);
}
</script>
<body onload = getinfo()>
<div align="center" id="l">设备信息</div>
<div align="center">
<table width="46%" id="tb">
<tbody>
<tr>
<th width="33%">设备</th>
<th width="34%">值</th>
<th width="33%">操作</th>
</tr>
<tr bgcolor="#FFFFFF">
<td>内存</td>
<td id='ram'>ram.value</td>
<td><!--<a href="on1"><button type="button1">开启</button></a><a href="off1"><button type="button4">关闭</button></a>-->-</td>
</tr>
<tr bgcolor="#FFFFFF">
<td>运行时间</td>
<td id='time'>time.value</td>
<td><!--<a href="on2"><button type="button2">开启</button></a><a href="off2"><button type="button5">关闭</button></a>-->-</td>
</tr>
</tbody>
</table>
</div>
</body>