Skip to content

Instantly share code, notes, and snippets.

@mcoffin
Created December 27, 2016 17:35
Show Gist options
  • Select an option

  • Save mcoffin/c209ca4a821909ccf0bd317f21cf1ee7 to your computer and use it in GitHub Desktop.

Select an option

Save mcoffin/c209ca4a821909ccf0bd317f21cf1ee7 to your computer and use it in GitHub Desktop.
module Util.Stream where
import Prelude
import Control.Monad.Aff (Aff, makeAff)
import Control.Monad.Eff (Eff)
import Control.Monad.Eff.Exception (EXCEPTION, Error)
import Control.Monad.ST (ST, newSTRef, modifySTRef, readSTRef, runST)
import Data.Monoid (class Monoid)
import Node.Encoding (Encoding(..))
import Node.Stream (Read, Readable, Stream, onData, onError, onEnd, onDataString)
readFullString :: forall w eff. Readable w (err :: EXCEPTION | eff) -> Aff (err :: EXCEPTION | eff) String
readFullString stream = makeAff handleData where
handleData :: (Error -> Eff (err :: EXCEPTION | eff) Unit) -> (String -> Eff (err :: EXCEPTION | eff) Unit) -> Eff (err :: EXCEPTION | eff) Unit
handleData onErr onSuccess = runST do
ref <- newSTRef ""
onError stream onErr
onEnd stream do
value <- readSTRef ref
onSuccess value
onDataString stream UTF8 \str -> do
modifySTRef ref $ flip (<>) str
pure unit
pure unit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment