Last active
September 3, 2020 11:15
-
-
Save pravdomil/03f8607c9862a34db9281a44151ee46f to your computer and use it in GitHub Desktop.
Elm for Node.js
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
port module Main exposing (..) | |
type alias Input = | |
{ argv : List String, stdin : String } | |
type alias Output = | |
{ code : Int, stdout : String, stderr : String } | |
main : Program Input () () | |
main = | |
Platform.worker | |
{ init = \flags -> ( (), exit (run flags) ) | |
, update = \_ _ -> ( (), Cmd.none ) | |
, subscriptions = \_ -> Sub.none | |
} | |
run : Input -> Output | |
run { stdin, argv } = | |
let | |
result = | |
Ok "Hello word" | |
in | |
case result of | |
Ok value -> | |
Output 0 value "" | |
Err error -> | |
Output 1 "" ("I stopped because,\n" ++ error ++ "\n") | |
port exit : Output -> Cmd msg |
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
#!/usr/bin/env node | |
const main = () => | |
Promise.resolve() | |
.then(readStdin) | |
.then(stdin => run(process.argv, stdin)) | |
.then(v => exit(v.code, v.stdout, v.stderr)) | |
.catch(e => exit(1, "", String(e))) | |
const run = (argv, stdin) => | |
new Promise(resolve => { | |
require("./main.js") | |
.Elm.Main.init({ flags: { argv, stdin } }) | |
.ports.exit.subscribe(resolve) | |
}) | |
const exit = (code, stdout, stderr) => { | |
process.stdout.write(stdout) | |
process.stderr.write(stderr) | |
process.exit(code) | |
} | |
const readStdin = () => | |
new Promise(resolve => { | |
let buffer = "" | |
if (process.stdin.isTTY) { | |
resolve(buffer) | |
return | |
} | |
process.stdin.setEncoding("utf8") | |
process.stdin.on("readable", () => { | |
let chunk | |
while ((chunk = process.stdin.read())) { | |
buffer += chunk | |
} | |
}) | |
process.stdin.on("end", () => { | |
resolve(buffer) | |
}) | |
}) | |
main() |
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
set -e | |
cd "${0%/*}" | |
elm make src/Main.elm --output main.js --optimize | |
clear | |
node run.js |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment