提供接口: 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: '請求成功!'
};
});
複製代碼