背景
通过node调用生产环境脚本或命令,打印日志并实时传输到前端页面显示
环境配置
- 生产环境 linux系统
- node v8.12.0
- express v4.16.3
- socket.io v2.3.0
- socket.io-client v2.3.0
- 前端框架 angular6
代码实现
app.js
var express = require('express');
var server = express();
var httpServer = require('http').Server(server);
var io = require('socket.io')(httpServer);
io.on("connection", (socket) => {
socket.on('disconnect', function () {
console.log('disconnected');
});
})
io.of('log').on('connect', (socket) => {
console.log('log connect');
// socket.nsp.emit('message', '日志已连接');
})
httpServer.listen(8080, function () {
logger.info("启动端口:" + port);
});
router.get('/api/k8s/log', function (req, res, next) {
try {
let log$ = Sockets.io.of('/log');
// var ls = spawn(path.join('log.sh'));
// var ls = spawn("kubectl", ['logs', '-f', 'peer0-org1-7888c9696b-zjqdd', 'peer', '-n', 'baas']);
// kubectl logs -f peer0-org1-7888c9696b-zjqdd peer -n baas
// 生产环境脚本位置
var ls = spawn("sh",["/bin/log.sh"]);
// var ls = spawn(path.join('log.bat'));
ls.stdout.on('data', function (data) {
let buffer = Buffer.from(data);
logger.warn('>>>>>>',buffer.toString('utf-8'))
log$.emit("message", buffer.toString('utf-8'));
});
ls.stderr.on('data', (data) => {
logger.error(`stderr: ${data}`);
// 传输数据
log$.emit("message", data);
});
ls.on('exit', function (code) {
log$.emit("message", "socket-end");
});
ls.on('close', function (code) {
logger.warn('>>>close', code)
log$.emit("message", "socket-end");
});
} catch (error) {
logger.error(error)
}
res.send({ code: 200, data: {} });
})
client使用方法
import { Injectable } from "@angular/core";
import { Observable } from "rxjs";
import * as io from "socket.io-client";
@Injectable({
providedIn: "root",
})
export class MessageSocketService {
socket: SocketIOClient.Socket;
connect(url) {
if(this.socket) this.socket.disconnect();
return new Observable((observer) => {
// 初始化
this.socket = io(url);
// 接收消息
this.socket.on("message", (data) => {
observer.next(data);
});
});
}
}
getLog() {
let url =
location.port == "4200" ? "http://www.baoli.com:8080/log" : "/log";
this.http.get("/api/k8s/log").subscribe((d) => {});
this.socketService$ = this.socketService
.connect(url)
.subscribe((d: any) => {
this.datas.push(d.toString());
if (d == "socket-end") {
this.isDataLoading = false;
console.log("日志传输完成!");
}
// if (this.isRendering) {
// requestAnimationFrame(this.scroll.bind(this));
// }
});
}