提供接口: GET /devicenode
返回:web
启动服务 并在 app.js ⽂文件变动更后⾃自动重启 app.js 进程。bash
koa
、koa-router
做为 Web 服务框架current-processes
服务器器的全量量进程列列表lodash
进行排序查看 koa-router Demo 整理好思路服务器
const Koa = require('koa');
const Router = require('koa-router');
const app = new Koa();
const router = new Router();
const PORT = 4000;
const systemInfo = {
'系统类型': os.platform(),
'CPU型号': os.cpus()[0].model,
'总内存': (os.totalmem() / (1024 * 1024 * 1024)).toFixed(2) + ' GB',
'空闲内存': (os.freemem() / (1024 * 1024 * 1024)).toFixed(2) + ' GB'
};
router.get('/', async (ctx, next) => {
await next();
ctx.body = "Hello Koa";
})
router.get('/device', async (ctx, next) => {
await next();
ctx.body = "device Koa";
});
// 加载路由中间件
app.use(router.routes()).use(router.allowedMethods());
app.listen(PORT, () => {
console.log(`listening ${PORT}`);
});
复制代码
current-processes
获取失败。虽然以前知道 nodejs 有 I/O 的特性,可是不踩过永远都不知道是什么样的坑。app
// 以前错误的作法
router.get('/device', (ctx) => {
processes = ps.get(function(err, processes) {
const sorted = _.sortBy(processes, 'cpu');
const result = sorted.reverse();
return result;
});
ctx.response.status = 200
ctx.response.body = {
code: 0,
success: true,
data: {
systemInfo,
processes
},
messege: '请求成功!'
};
});
复制代码
使用 async
、await
和 Promise
,确保 current-processes
获取完成再继续返回框架
router.get('/device', async (ctx, next) => {
await next();
const processes = await new Promise((resolve, reject) => {
ps.get(function(err, processes) {
const sorted = _.sortBy(processes, 'cpu');
const result = sorted.reverse();
resolve(result);
});
})
ctx.response.status = 200
ctx.response.body = {
code: 0,
success: true,
data: {
systemInfo,
processes
},
messege: '请求成功!'
};
});
复制代码