Skip to content

Instantly share code, notes, and snippets.

@TooTallNate
Created June 20, 2018 05:37
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save TooTallNate/639790535e5b728b32db3279471a64a4 to your computer and use it in GitHub Desktop.
Save TooTallNate/639790535e5b728b32db3279471a64a4 to your computer and use it in GitHub Desktop.
Write JavaScript functions - use as bash functions
#!/bin/bash
jsfunc() {
local code="$(cat)"
local fn="$(cat <<EOFF
$1() {
node <(cat <<EOF
require('stream').Readable.prototype.then = function (...args) { return new Promise((res, rej) => { const bufs = []; this.on('error', rej).on('data', buf => bufs.push(buf)).on('end', () => res(Buffer.concat(bufs))); }).then(...args) };
(async () => {
${code}
})().then(val => typeof val !== 'undefined' && console.log(typeof val === 'string' ? val : JSON.stringify(val, null, 2))).catch(err => console.error(err.stack) || process.exit(1));
EOF
) "\$@"
}
EOFF
)"
eval "${fn}"
}
#!/bin/bash
source ./jsfunc.sh
jsfunc my_js_func <<EOF
const stdin = String(await process.stdin);
return (stdin + ' ' + process.argv[2]).toUpperCase();
EOF
printf hello | my_js_func world
# HELLO WORLD
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment