Skip to content

Instantly share code, notes, and snippets.

@jrop
Last active December 20, 2022 18:34
Show Gist options
  • Save jrop/e826d38a9229cd5f55d597296649e599 to your computer and use it in GitHub Desktop.
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
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();
};
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