Last active
September 6, 2022 01:25
-
-
Save sigmaSd/e3231a191323629b1c97643f8f260978 to your computer and use it in GitHub Desktop.
Install a javascript function as an executable
This file contains 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
import cache_dir from "https://deno.land/x/[email protected]/cache_dir/mod.ts"; | |
import { ensureDirSync } from "https://deno.land/[email protected]/fs/ensure_dir.ts"; | |
export interface Options { | |
prelude?: string; | |
permissions?: string[]; | |
} | |
// deno-lint-ignore no-explicit-any | |
export default function installFn(fn: any, options?: Options) { | |
const name = fn.name; | |
if (!name) { | |
throw "fn name is required"; | |
} | |
const body: string = fn.toString(); | |
let content; | |
if (body.includes("=>")) { | |
content = ` | |
const ${name} = ${body} | |
const output = ${name}(...Deno.args) | |
console.log(output) | |
`; | |
} else { | |
// TODO | |
throw "unrecognized function type"; | |
} | |
if (options?.prelude) { | |
content = options.prelude + "\n" + content; | |
} | |
const installDir = `${cache_dir()}/deno-install-fn/`; | |
ensureDirSync(installDir); | |
const fnPath = `${installDir}/${name}.ts`; | |
Deno.writeTextFileSync(fnPath, content); | |
Deno.spawnSync("deno", { | |
args: ["fmt", fnPath], | |
}); | |
Deno.spawnSync("deno", { | |
args: options?.permissions | |
? ["install", "-f", ...options.permissions, fnPath] | |
: ["install", "-f", fnPath], | |
stdout: "inherit", | |
stderr: "inherit", | |
}); | |
console.log(`%c${name}%c was succefully installed!`, "color:blue", ""); | |
} |
Author
sigmaSd
commented
Aug 22, 2022
How it works
1- create a script with the name of the function
2- Write the script content (to $cache/deno-install-fn/script): Evaluate Deno.args as input to the function body and write it to stdout
3- deno install scriptPath
i you have ~/.deno/bin in your path , this make it very convenient as the function will become immediately available
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment