Recently, the project needs to write a function of CMD command line window. The realization of this function has changed several versions and checked a lot of information. I have to say that the official website document is really really difficult to understand

1. Install the version

First, install the plug-in. For Xtermd, I only used xterm and xterm-Addon-fit. Xterm-add-fit is a plug-in that allows the command line window to size itself. I use xterm.js version 4.13, please pay attention to distinguish between 3.x and 4.x version, there is a way to get keyboard input is different (see: blog.csdn.net/weixin_3831… npm install xterm.js –save npm install xterm-add-fit –save

2. Introduce plug-ins

Within the page, introduce xterm.js and xterm-Addon-fit

import { Terminal } from 'xterm'
import { FitAddon } from 'xterm-addon-fit'
import 'xterm/css/xterm.css'
import 'xterm/lib/xterm.js'
Copy the code

3. Using xterm. Js

Socket message callback function where I did some processing on the console text color control, there are colorful ideas, if you need to take a look, I only set the text color, can also set the background color, font bold and so on.

// Initialize websocket initSocket () {let url = "if (process.env.node_env === 'development') {url = '192.168.1.149:2224' //' ws address} 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() }, // open the connection openSocket () {this.socket.onOpen = () => {this.initterm () this.sendData(1)}}, CloseSocket () {this.socket.onclose = () => {// console // this.sendData()}}, ErrorSocket () {this.socket.onError = () => {this.$message.error(' Websoket connection failed, please refresh! ')}}, // 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 ('{')! Parse (data) this.sshprompt = data. Prompt if (data. Status === 'status') {color = '\x1b[94m' // blue} Else if (data.status === 'error') {color = '\x1b[91m' // red} else if (data.status === = 'good') {color = '\x1b[92m' // Else if (data.status === 'warning') {color = '\x1b[93m' // yellow} else {color = '\x1b[37m' // white} 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) } } },Copy the code

(2) The code to initialize xterm is a bit long. To summarize what the following code does:

Keyboard input characters, splicing commands, after encountering the return to send the command to the back end, the back end returns the command running results output to the interface;

Save the input commands to sessionStorage, use up and down keys to switch commands;

TAB key completion function, this is to call the back-end interface to achieve;

// Initialize terminal 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 '); Function resizeScreen() {// console.log("size", size); try {fitadon.fit ();  } catch (e) { console.log("e", e.message); }} window.addeventListener ("resize", resizeScreen) term.focus() Function (key) {if(key.charcodeat (0) == 13) {// Enter if(that.command === 'clear') {term.clear()} If (that.man.trim ().length === 0) {term.prompt()} else {// Save let commands = localstorage.getitem ('commands')?  JSON.parse(localStorage.getItem('commands')) : [] commands.push(that.command) localStorage.setItem('commands', JSON.stringify(commands)) localStorage.setItem('index', Command.length) that.sendData(0)} that.command = ""} else if (key === '\u001b[A') {// Upward direction 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) {// Remove the existing command 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') {// down direction 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) {// Delete the existing command 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.com mand} // TAB complete 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 },Copy the code

These are the basic steps and core code. If you have any questions, please share them in the comments section