9
votes

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

2
What error did you get from readFile?Phil Freeman
Another way to read JSON files on Node is to use require.Phil Freeman
I get Unknown value bind. Maybe I forgot import Prelude, hang on…0dB
No import Prelude is definitely the issue then.Phil Freeman
Thanks, I got it working. I also had to switch to readTextFile and writeTextFile to get away from type Buffer so as to be able to process the file, and had to find out how to specify the encoding: Node.Encoding.UTF8.0dB

2 Answers

9
votes

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"
3
votes

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