【问题标题】:Node JS - Backspace not working in Node-Pty TerminalNode JS - Backspace 在 Node-Pty 终端中不起作用
【发布时间】:2021-12-19 13:02:00
【问题描述】:

我有这个简单的代码

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 事件到的毫秒数,并将一个对象推入recording数组,这个对象有两个属性,第一个是延迟,第二个是文本。当on exit 事件触发时,它会简单地关闭终端并将recording 数组保存到名称等于变量filename 的json 文件中

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

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

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

我该如何解决这个问题?

这就是我的 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 版本:v16.11.1
  • 我的 NPM 版本:8.1.2
  • 我的 Linux 发行版:带有 XFCE 4 的 Arch Linux

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

【问题讨论】:

  • 您能否更准确一些,请描述一下您在 gif 视频的哪一行看到了额外的空间,看起来不错
  • 我用的是ubuntu,在ubuntu中无法重现,可能是arch中的键盘映射问题。可以使用运行此setxkbmap -model evdev -layout us -variant colemak 来更改键盘布局。
  • MANNNNNNNNNNNNNNNNNNNN!!!!!!!!!实际上,您的答案并没有完全起作用,因为它确实改变了我的整个键盘布局,但是当我运行 setxkbmap -layout us 时,它现在就起作用了!!!!!!!!!

标签: javascript node.js shell terminal pty


【解决方案1】:

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

我运行了以下命令setxkbmap -layout us,将我的键盘布局更改为美国,现在它可以工作了

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-17
    • 1970-01-01
    • 2021-12-04
    • 1970-01-01
    • 2017-12-28
    • 2019-03-19
    • 1970-01-01
    • 2018-03-03
    相关资源
    最近更新 更多