From 7fa5ab5bc6b4a8c564198552fd6a256bb7438dc9 Mon Sep 17 00:00:00 2001 From: wancat Date: Thu, 3 Aug 2023 18:04:22 +0800 Subject: [PATCH] Create a pty cli, not useful --- packages/cli/index.js | 50 +++++++++++++++++++++++++++++++++++++++++++ yarn.lock | 7 ++++++ 2 files changed, 57 insertions(+) create mode 100644 packages/cli/index.js diff --git a/packages/cli/index.js b/packages/cli/index.js new file mode 100644 index 0000000..1e87ff1 --- /dev/null +++ b/packages/cli/index.js @@ -0,0 +1,50 @@ +import { stdin, stdout, exit } from 'process' +import os from 'os' +import pty from 'node-pty' + +stdin.setRawMode(true) +stdin.resume() +stdin.setEncoding('utf8') + +// Create a new pseudoterminal +const shell = os.platform() === 'win32' ? 'powershell.exe' : 'bash' +const ptyProcess = pty.spawn(shell, [], { + name: 'xterm-color', + cols: 80, + rows: 30, + cwd: process.env.HOME, + env: process.env, +}) + +// Listen for output data +ptyProcess.on('data', function (data) { + // Intercept and process the output here + stdout.write(data) +}) + +// Write a command to the pseudoterminal +ptyProcess.write('ls\r') + +let commandBuffer = '' + +stdin.on('data', (key) => { + if (key === '\u0004') { + exit() + } else if (key === '\r') { + // User pressed enter, log and execute the command + console.log('User command: ', commandBuffer) + commandBuffer = '' + } else if (key === '\u007F') { + // User pressed backspace, remove the last character from the buffer + commandBuffer = commandBuffer.slice(0, -1) + } else { + // Add the typed character to the command buffer + commandBuffer += key + } + ptyProcess.write(key) +}) + +// Listen for exit event +ptyProcess.on('exit', function (exitCode) { + console.log('Process exited with code: ', exitCode) +}) diff --git a/yarn.lock b/yarn.lock index e7d8450..9f1b4b7 100644 --- a/yarn.lock +++ b/yarn.lock @@ -3612,6 +3612,13 @@ node-int64@^0.4.0: resolved "https://registry.yarnpkg.com/node-int64/-/node-int64-0.4.0.tgz#87a9065cdb355d3182d8f94ce11188b825c68a3b" integrity sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw== +node-pty@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/node-pty/-/node-pty-1.0.0.tgz#7daafc0aca1c4ca3de15c61330373af4af5861fd" + integrity sha512-wtBMWWS7dFZm/VgqElrTvtfMq4GzJ6+edFI0Y0zyzygUSZMgZdraDUMUhCIvkjhJjme15qWmbyJbtAx4ot4uZA== + dependencies: + nan "^2.17.0" + node-releases@^2.0.12: version "2.0.13" resolved "https://registry.yarnpkg.com/node-releases/-/node-releases-2.0.13.tgz#d5ed1627c23e3461e819b02e57b75e4899b1c81d"