想在工具里面执行 shell 进行部分命令行交互
基于 微软开源的 xterm.js 和 nodepty
https://github.com/microsoft/xterm.js 前端
https://github.com/microsoft/node-pty 后台
index.html 文件
<!doctype html> <html> <link rel="stylesheet" href="node_modules/xterm/css/xterm.css" /> <body> <div id="terminal"></div> </body> <script> // No idea what these are about. Just copied them from the demo code window.require = window.parent.require; var global_xterm = undefined; var global_pty = undefined; function testbtnclick(){ var os = require('os'); var process = require('process'); var pty = require('node-pty'); var Terminal = require('xterm').Terminal; var FitAddon = require('xterm-addon-fit').FitAddon // Initialize node-pty with an appropriate shell const shell = process.env[os.platform() === 'win32' ? 'COMSPEC' : 'SHELL']; console.log("shell = " + shell); console.log("process.env = ", process.env); const ptyProcess = pty.spawn(shell, [], { name: 'xterm-color', cols: 80, rows: 34, cwd: process.cwd(), env: process.env }); // Initialize xterm.js and attach it to the DOM const xterm = new Terminal({ cols: 80, rows: 34, cursorBlink: true, }); xterm.open(document.getElementById('terminal')); global_xterm = xterm; global_pty = ptyProcess; const fitaddon = new FitAddon(); xterm.loadAddon(fitaddon); fitaddon.fit() // Setup communication between xterm.js and node-pty xterm.onData(data => ptyProcess.write(data)); ptyProcess.on('data', function (data) { xterm.write(data); }); } function shellEnter(workpath){ if (global_pty){ global_pty.write("cd " + workpath +"\n"); setTimeout(() => { global_pty.write("fastlane deliver \n"); }, 2); } } </script> </html>
一定要注意 nodepty 和 electron 的版本要对应上 否则 会有各种各样的报错 当初在这里纠结了将近3天 简直崩溃。
node-pty 有对应 nodejs 的版本 还有对应 electron 的版本 无法通用
这里贴出我 package.json 文件, 这里标记了 electron node-pty 和 nodej 对应的版本
{ "name": "fileinfotool", "version": "0.1.0", "main": "main.js", "scripts": { "rebuild": "electron-rebuild -f -w node-pty" }, "dependencies": { "electron": "^5.0.11", "iconv-lite": "^0.5.0", "node-pty": "^0.8.1", "xterm": "^4.1.0", "xterm-addon-fit": "^0.2.1", "image-size": "^0.7.4" }, "devDependencies": { "electron-rebuild": "^1.8.6" } }