Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a file in PureScript (readFile)

Tags:

purescript

While testing, I’d like to read and write a file from and to disk (JSON in, JSON out). How do I do this in PureScript? In Haskell I have something like

main :: IO ()
main = do
  input <- readFile "input.json"
  writeFile "output.json" $ process input

All my attempts so far have failed, including trying to use readFile from import Node.FS.Sync.

BTW, if there is any other (better) way of reading in my JSON file, let me know. (I am not a JavaScript expert but I would like to port some — strict — Haskell code to JS so that it can be used elsewhere.)

like image 920
0dB Avatar asked Feb 29 '16 16:02

0dB


2 Answers

Or with purescript 0.12

module Main where

import Prelude
import Effect (Effect)
import Effect.Console (log)

import Node.Encoding (Encoding(..))
import Node.FS.Sync (readTextFile)

main :: Effect Unit
main = do
  log =<< readTextFile UTF8 "input.json"
like image 162
Ulve Avatar answered Nov 01 '22 01:11

Ulve


Here's a full working example that reads and prints a file.

module Main where

import Prelude (Unit)

import Control.Bind ((=<<))
import Control.Monad.Eff (Eff)
import Control.Monad.Eff.Console (CONSOLE, log)
import Control.Monad.Eff.Exception (EXCEPTION)

import Node.Encoding (Encoding(..))
import Node.FS (FS)
import Node.FS.Sync (readTextFile)

main :: forall e. Eff (console :: CONSOLE, exception :: EXCEPTION, fs :: FS | e) Unit
main = do
  log =<< readTextFile UTF8 "input.json"

Dependencies:

  • purescript-console
  • purescript-eff
  • purescript-math
  • purescript-node-fs-aff
  • purescript-control
like image 33
Chris Martin Avatar answered Oct 31 '22 23:10

Chris Martin