这是一个相当广泛的问题,但也很有趣。我发现很难仅用代码来回答这个问题,但也许你会发现我的回答很有用。
有几种方法可以实现:
- 将 ANSI 字符串转换为 HTML 并将它们发送给客户端
- 将 ANSI 字符串发送给客户端并要求他们进行转换
我选择了第二个,因为您似乎在后端使用 Python,而且我并不真正了解 Python 网络编程,无法为您提供完整的示例。在这种情况下,选项 2 限制了您必须在 Python 中复制的代码量才能获得如下所示的功能。
您可以找到包含前端和后端 (NodeJS) 代码 here 的完整示例。后端只是一个 websocket 服务器,它将命令的输出通过管道传递给传入的连接。
对于输出,我尝试使用apt update 和top,但apt update 在从NodeJS 调用时不会呈现颜色输出,top 会抱怨缺少tty。相反,我决定使用一个简单的 shell 脚本来生成带有随机 ANSI 颜色的字符串。这个逻辑大部分是从this answer借来的。
前端是一个非常简单的Console VueJS 组件,我在下面进行了描述。所有繁重的工作都由ansi_up 库完成,我只是将它的输出直接用作组件的 HTML 内容。
<template>
<div class="console" v-html="html">
</div>
</template>
<script>
import AnsiUp from 'ansi_up'
export default {
name: 'shell',
props: ['socket'],
data () {
return {
ansi: undefined,
content: ''
}
},
computed: {
html () {
// Ensures we have some semblance of lines
return this.ansi.ansi_to_html(this.content).replace(/\n/gm, '<br>')
}
},
watch: {
socket () {
this.socket.on('data', data => {
this.content += data
})
this.socket.send('ready')
}
},
beforeMount () {
this.ansi = new AnsiUp()
},
updated () {
// auto-scroll to the bottom when the DOM is updated
this.$el.scrollTop = this.$el.scrollHeight
}
}
</script>
<style lang="scss" scoped>
.console {
font-family: monospace;
text-align: left;
background-color: black;
color: #fff;
overflow-y: auto;
}
</style>