Created
June 20, 2018 05:37
-
-
Save TooTallNate/639790535e5b728b32db3279471a64a4 to your computer and use it in GitHub Desktop.
Write JavaScript functions - use as bash functions
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
#!/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}" | |
} |
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
#!/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