Skip to content

Commit

Permalink
Add example of reading from stdin (#18)
Browse files Browse the repository at this point in the history
  • Loading branch information
blaix authored Jan 3, 2025
1 parent f749559 commit 54e5226
Show file tree
Hide file tree
Showing 6 changed files with 102 additions and 1 deletion.
3 changes: 2 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ browser_examples := \

node_examples := \
cat\
http-server
http-server\
read_stdin

all_examples := $(browser_examples) $(node_examples)

Expand Down
7 changes: 7 additions & 0 deletions read_stdin/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Example reading from stdin

```
npm install
npx gren make src/Main.gren
node app
```
17 changes: 17 additions & 0 deletions read_stdin/gren.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"type": "application",
"platform": "node",
"source-directories": [
"src"
],
"gren-version": "0.5.2",
"dependencies": {
"direct": {
"gren-lang/core": "6.0.0",
"gren-lang/node": "5.0.0"
},
"indirect": {
"gren-lang/url": "5.0.0"
}
}
}
48 changes: 48 additions & 0 deletions read_stdin/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions read_stdin/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"private": true,
"dependencies": {
"gren-lang": "^0.5.2"
}
}
22 changes: 22 additions & 0 deletions read_stdin/src/Main.gren
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
module Main exposing (main)

import Node
import Stream
import Node exposing (Environment)
import Init
import Task


main : Node.SimpleProgram a
main =
Node.defineSimpleProgram init


init : Environment -> Init.Task (Cmd a)
init env =
Stream.writeStringAsBytes "What is your name?\nName: " env.stdout
|> Task.andThen (\_ -> Stream.readBytesAsString env.stdin)
|> Task.map (Maybe.withDefault "") -- ignoring if we can't convert stdin bytes to string
|> Task.andThen (\name -> Stream.writeStringAsBytes ("Hi, " ++ name) env.stdout)
|> Task.onError (\_ -> Task.succeed env.stdout) -- ignoring all stream-related errors
|> Node.endSimpleProgram

0 comments on commit 54e5226

Please sign in to comment.