Last active
December 20, 2022 18:34
-
-
Save jrop/e826d38a9229cd5f55d597296649e599 to your computer and use it in GitHub Desktop.
A very simplistic command shell for use in environments that give a Node REPL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
global._poorMansShell = () => { | |
const { spawn } = require("child_process"); | |
const fs = require("fs"); | |
const path = require("path"); | |
const readline = require("readline"); | |
let CURRENT_DIR = process.cwd(); | |
const READLINE = readline.createInterface({ | |
input: process.stdin, | |
output: process.stdout, | |
}); | |
const getCdIfPresent = (cmd) => { | |
const match = /^\s*cd\s+(.*)$/.exec(cmd); | |
if (match) return match[1]; | |
}; | |
const showPromptForCommand = () => | |
READLINE.question(`${CURRENT_DIR} $ `, (cmd) => { | |
const cd = getCdIfPresent(cmd); | |
if (cd) { | |
if (!cd.startsWith("/")) { | |
CURRENT_DIR = path.resolve(path.join(CURRENT_DIR, cd)); | |
} else { | |
CURRENT_DIR = cd; | |
} | |
return showPromptForCommand(); | |
} | |
fs.writeFileSync(`${__dirname}/tmp.sh`, cmd); | |
const proc = spawn("sh", [`${__dirname}/tmp.sh`], { | |
cwd: CURRENT_DIR, | |
stdio: "inherit", | |
}); | |
proc.on("close", () => showPromptForCommand()); | |
}); | |
showPromptForCommand(); | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
global._sh = function (cmd) { | |
const { execSync } = require("child_process"); | |
const output = execSync(cmd).toString("utf8"); | |
console.log(output); | |
return output; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment