节点 JS - 退格键在 Node-Pty 终端中不起作用

Node JS - Backspace not working in Node-Pty Terminal

我有这个简单的代码

const os = require('os')
const pty = require('node-pty')
const process = require('process')
const { msleep } = require('sleep');
const { readFileSync, writeFileSync } = require('fs');
const { exit } = require('process');

const usage = `Usage: term-record [OPTION]

OPTION:
  play [Filename]        Play a recorded .json file
  record [Filename]      Record your terminal session to a .json file`

var shell = os.platform() === 'win32' ? 'powershell.exe' : 'bash'
var lastRecordTimestamp = null
var recording = []
var args = process.argv
args.splice(0, 2)

function getDuration() {
    var now = new Date().getMilliseconds()
    var duration = now - lastRecordTimestamp
    lastRecordTimestamp = new Date().getMilliseconds()
    return duration
}

function play(filename) {
    try {
        var data = readFileSync(filename, { encoding: 'utf8', flag: 'r'})
    } catch (err) {
        if (err.code == 'ENOENT') {
            console.error("Error: File Not Found!")
            exit(1)
        } else {
            console.error(err)
            exit(1)
        }
    }

    try {
        data = JSON.parse(data)     
    } catch (err) {
        console.error("Error: Invalid File!");
        exit(1)
    }

    console.log("------------ STARTING ------------");
    for (let i = 0; i < data.length; i++) {
        process.stdout.write(data[i].content);
        msleep(data[i].delay)
    }
    console.log("-------------- END ---------------");
}

function record(filename) {
    var ptyProcess = pty.spawn(shell, [], {
        name: 'TermRecord Session',
        cols: process.stdout.columns,
        rows: process.stdout.rows,
        cwd: process.env.HOME,
        env: process.env
    });

    process.stdout.setDefaultEncoding('utf8');
    process.stdin.setEncoding('utf8')
    process.stdin.setRawMode(true)
    process.stdin.resume();

    ptyProcess.on('data', function(data) {
        process.stdout.write(data)
        var duration = getDuration();

        if (duration < 5) {
            duration = 100
        }

        recording.push({
            delay: Math.abs(duration),
            content: data
        });
    });

    ptyProcess.on('exit', () => {
        process.stdin.setRawMode(false);
        process.stdin.pause()

        recording[0].delay = 1000
        try {
            writeFileSync(filename, JSON.stringify(recording, null, '\t')); // JSON.stringify(recording, null, '\t') For Tabs
        } catch (err) {
            console.log(err);
        }
    })

    var onInput = ptyProcess.write.bind(ptyProcess)
    process.stdin.on('data', onInput)
}

if (args.length === 2) {
    var file = args[1]
    if (args[0] == "record") {
        console.info("Setting App Mode to 'Record'")
        console.info("Setting Output file To '" + file + "'")
        record(file)
    }
    if (args[0] == "play") {
        console.info("Setting App Mode to 'Play'")
        console.info("Setting Input file To '" + file + "'")
        play(file)
    }
} else {
    console.log(usage);
}

record 函数接受一个参数 filename,然后使用 node-pty 模块启动一个新终端,当 on data 事件发生时,它简单地计算从上次触发这个on data事件,把一个object压入recording数组,这个object有两个属性,第一个是延迟,第二个是文本。当 on exit 事件触发时,它只是关闭终端并将 recording 数组保存到名称等于变量 filename

的 json 文件中

play函数接受一个参数filename,然后从文件中读取数据并将其解析为包含多个object的JavaScript数组,并且如果出现问题,它会抛出错误。解析后它简单地使用 for 循环遍历数组并将数据写入控制台并等待几毫秒。

问题是,当我录制我的会话时,当我按 Backspace 键删除一个字符时,它会奇怪地在它们之间放置一个 space,如下所示:

在 gif 中,在我 运行 第一个命令并输入 ls -ls 之后,我按了 Backspace 2 次,这结果出现奇怪的空白 space 2 次。 在我按下回车键后,它显示了一个错误 ls: cannot access '-': No such file or directory,这意味着 Backspace 键从输入中删除了 2 个字符,但它执行了 ls - ls -ls 但由于某些原因,当我按 Backspace 两次时,这两个字符没有从控制台中删除,而是添加了一个奇怪的空白 space

我该如何解决这个问题?

这是我的 package.json 的样子:

{
  "name": "term-record",
  "version": "0.0.1",
  "description": "A Simple Terminal Session Recorder",
  "main": "src/index.js",
  "scripts": {
    "start": "node src/index.js"
  },
  "author": "ADITYA MISHRA",
  "license": "MIT",
  "dependencies": {
    "node-pty": "^0.10.1",
    "sleep": "^6.3.0"
  }
}

我尝试切换到 nodejs 版本 14.18.1-1,但这也没有帮助

由于我的键盘布局选择不当,导致后退space键添加了一个space。

我 运行 以下命令 setxkbmap -layout us,将我的键盘布局更改为美式,现在可以使用了