Skip to content

Instantly share code, notes, and snippets.

@pravdomil
Last active September 3, 2020 11:15
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pravdomil/03f8607c9862a34db9281a44151ee46f to your computer and use it in GitHub Desktop.
Save pravdomil/03f8607c9862a34db9281a44151ee46f to your computer and use it in GitHub Desktop.
Elm for Node.js
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
#!/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()
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