Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.