最近项目需要写一个cmd命令行窗口的功能,实现这个功能来来回回换了好几个版本,查了好多的资料,不得不说官网文档真的真的很难看懂,在此记录一下我是怎么实现的~
1.安装版本
首先,安装插件。关于Xterm 我只用到了xterm以及xterm-addon-fit这两个插件,xterm-add-fit这个插件是用于让命令行窗口自适应大小的。我xterm.js使用的是4.13的版本,大家注意区分3.x和4.x的版本,里面有个获取键盘输入的方法是不一样的(具体请看:https://blog.csdn.net/weixin_38318244/article/details/103908129)。
npm install xterm.js --save
npm install xterm-add-fit --save
2.引入插件
在页面内,引入xterm.js以及xterm-addon-fit
import { Terminal } from 'xterm'
import { FitAddon } from 'xterm-addon-fit'
import 'xterm/css/xterm.css'
import 'xterm/lib/xterm.js'
3.使用xterm.js
(1)连接socket
socket消息回调函数那里我做了一些关于控制台文本颜色控制的处理,有点子花花绿绿的,如果有需要的话,可以看一下,我这只设置了文本颜色,还可以设置背景色,字体加粗之类的。
// 初始化websocket
initSocket () {
let url = ''
if (process.env.NODE_ENV === 'development') {
url = '192.168.1.149:2224' //` ws地址
} else {
url = this.baseUrl
url = url.split('//')[1]
}
// console.log(url)
this.socket = new WebSocket((location.protocol === 'http:' ? 'ws://' : 'wss://') + url + '/web/consoleWebsocket')
this.openSocket()
this.closeSocket()
this.errorSocket()
this.messageSocket()
},
// 打开连接
openSocket () {
this.socket.onopen = () => {
this.initTerm()
this.sendData(1)
}
},
// 关闭连接
closeSocket () {
this.socket.onclose = () => {
// console
// this.sendData()
}
},
// 连接错误
errorSocket () {
this.socket.onerror = () => {
this.$message.error('websoket连接失败,请刷新!')
}
},
// 消息回调
messageSocket () {
this.socket.onmessage = (res) => {
// console.log(res)
if (res.data.length !== 0) {
// console.log(res.data.repeat())
let data = res.data
let result = data
let color = '\x1b[37m'
// console.log(typeof data)
if (res.data.substr(0,1).indexOf('{') !== -1) {
data = JSON.parse(data)
this.sshPrompt = data.prompt
if (data.status === 'status') {
color = '\x1b[94m' // 蓝色
} else if (data.status === 'error') {
color = '\x1b[91m' // 红色
} else if (data.status === 'good') {
color = '\x1b[92m' // 绿色
} else if (data.status === 'warning') {
color = '\x1b[93m' // 黄色
} else {
color = '\x1b[37m' // 白色
}
result = data.data
this.term.write('\r\n'+ color + result)
if (data.busy) {
return
}
} else {
this.term.write('\r\n' + color + result)
}
this.term.prompt()
// setTimeout(, 2000)
}
}
},
(2)初始化xterm
代码有点长,概括一下下面的代码主要实现了哪些功能:
键盘输入字符,拼接命令,遇到回车之后就将命令发送给后端,后端返回命令运行结果输出到界面;
保存输入过的命令到sessionStorage内,通过上下键可以切换命令;
tab键补全功能,这个是调用后端接口实现的;
// 初始化终端
initTerm () {
this.consoleLoading = true
let that = this
let termContainer = document.getElementById('terminal')
localStorage.setItem('commands', '')
that.cols = termContainer.offsetWidth / 9
that.rows = termContainer.offsetHeight / 9
const term = new Terminal({
cursorBlink: true,
cols: parseInt(that.cols),
theme: {
// foreground: "#7e9192", //字体
fontFamily: 'DejaVu',
lineHeight: 16
}
})
let fitAddon = new FitAddon()
term.loadAddon(fitAddon)
term.open(termContainer)
term.prompt = function () {
let color = '\x1b[33m'
term.write('\r\n' + color + that.sshPrompt + '$\x1b[0m ');
}
fitAddon.fit()
// 内容全屏显示-窗口大小发生改变时
function resizeScreen() {
// console.log("size", size);
try {
fitAddon.fit();
} catch (e) {
console.log("e", e.message);
}
}
window.addEventListener("resize", resizeScreen)
term.focus() // 光标聚焦
// 添加事件监听器,支持输入方法
term.onData( function (key) {
if (key.charCodeAt(0) == 13) { // 回车
if(that.command === 'clear') {
term.clear()
}
if (that.command.trim().length === 0) {
term.prompt()
} else {
// 保存命令
let commands = localStorage.getItem('commands') ? JSON.parse(localStorage.getItem('commands')) : []
commands.push(that.command)
localStorage.setItem('commands', JSON.stringify(commands))
localStorage.setItem('index', commands.length)
that.sendData(0)
}
that.command = ''
} else if (key === '\u001b[A') { // 向上方向
let commands = localStorage.getItem('commands') ? JSON.parse(localStorage.getItem('commands')) : []
// console.log(commands)
let index = localStorage.getItem('index') ? localStorage.getItem('index') : commands.length
index = parseInt(index)
if (commands.length && index < commands.length + 1 && index > 0) {
// 删除现有命令
for (let i = 0; i < that.command.length; i++) {
if (term._core.buffer.x > (that.sshPrompt.length + 2)) {
term.write('\b \b')
}
}
that.command = commands[index - 1]
term.write(that.command)
localStorage.setItem('index', index - 1)
}
} else if (key === '\u001b[B') { // 向下方向
let commands = localStorage.getItem('commands') ? JSON.parse(localStorage.getItem('commands')) : []
let index = localStorage.getItem('index') ? localStorage.getItem('index') : commands.length
index = parseInt(index)
if (commands.length && index < commands.length - 1 && index > -1) {
// 删除现有命令
for (let i = 0; i < that.command.length; i++) {
if (term._core.buffer.x > (that.sshPrompt.length + 2)) {
term.write('\b \b')
}
}
that.command = commands[index + 1]
term.write(that.command)
localStorage.setItem('index', index + 1)
}
} else if (key.charCodeAt(0) === 9) { // tab键
let params = {
consoleUUID: that.activeMsf,
cmd: that.command
}
// tab补全
that.$apis.readTabsComplete(params).then((res) => {
if (res.code === 200) {
if (res.data.length) {
for (let i = 0; i < that.command.length; i++) {
term.write('\b \b')
}
let data = res.data.join('\r\n')
that.command = res.data[res.data.length - 1]
if (res.data.length > 1) {
term.write('\r\n')
term.write(data)
term.prompt()
term.write(res.data[res.data.length - 1])
} else {
term.write(that.command)
}
}
} else {
that.$message.error(res.message())
}
})
} else if (key.charCodeAt(0) === 127) {
if (term._core.buffer.x > (that.sshPrompt.length + 2)) {
term.write('\b \b')
that.command = that.command.substr(0, that.command.length - 1)
}
} else{
that.command += key
term.write(key)
}
})
that.term = term
},
大致的步骤和核心代码就是这些啦,如果有问题的话,可以一起在评论区交流下~