11

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.)

0dB
  • 675
  • 5
  • 13

2 Answers2

11

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"
Ulve
  • 299
  • 2
  • 5
4

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
Josh
  • 784
  • 6
  • 13
Chris Martin
  • 30,334
  • 10
  • 78
  • 137