Reading Files in PureScript

Here’s the translation of the Go code for reading files to PureScript, along with explanations:

module Main where

import Prelude

import Effect (Effect)
import Effect.Console (log)
import Node.Encoding (Encoding(..))
import Node.FS.Sync as FS
import Node.Buffer as Buffer
import Data.Either (Either(..))

-- Helper function to handle errors
check :: forall a. Either String a -> Effect a
check (Left err) = do
  log err
  throw err
check (Right value) = pure value

main :: Effect Unit
main = do
  -- Read entire file contents into memory
  dat <- FS.readTextFile UTF8 "/tmp/dat"
  log dat

  -- Open file for more controlled reading
  f <- FS.openSync "/tmp/dat" FS.R

  -- Read some bytes from the beginning of the file
  b1 <- Buffer.create 5
  n1 <- FS.readSync f b1 0 5 0
  s1 <- Buffer.toString UTF8 b1
  log $ show n1 <> " bytes: " <> s1

  -- Seek to a known location and read from there
  FS.seekSync f 6 FS.SeekAbsolute
  b2 <- Buffer.create 2
  n2 <- FS.readSync f b2 0 2 6
  s2 <- Buffer.toString UTF8 b2
  log $ show n2 <> " bytes @ 6: " <> s2

  -- Seek relative to current position
  FS.seekSync f 4 FS.SeekCurrent

  -- Seek relative to end of file
  FS.seekSync f (-10) FS.SeekEnd

  -- Read at least 2 bytes
  b3 <- Buffer.create 2
  n3 <- FS.readSync f b3 0 2 6
  s3 <- Buffer.toString UTF8 b3
  log $ show n3 <> " bytes @ 6: " <> s3

  -- Rewind to beginning of file
  FS.seekSync f 0 FS.SeekAbsolute

  -- Close the file when done
  FS.closeSync f

This PureScript code demonstrates various file reading operations, similar to the original Go example. Here are some key points:

  1. We use the Node.FS.Sync module for synchronous file operations, which is similar to the os package in Go.

  2. Instead of a check function that panics, we use a check function that logs the error and throws it.

  3. PureScript doesn’t have a direct equivalent to Go’s slices, so we use Node.Buffer for byte operations.

  4. The Seek operations are performed using FS.seekSync with different SeekMode values.

  5. PureScript doesn’t have a built-in buffered reader like Go’s bufio, so we don’t include an equivalent to the bufio.NewReader example.

  6. Error handling in PureScript is typically done using the Either type, which we use in our check function.

To run this program, you would need to set up a PureScript project with the necessary dependencies, compile it, and then run it with Node.js. The output would be similar to the Go version, displaying the contents of the file and the results of various read operations.

Remember to create a /tmp/dat file with some content before running the program:

$ echo "hello" > /tmp/dat
$ echo "purescript" >> /tmp/dat

This example demonstrates how to perform various file reading operations in PureScript, including reading entire files, seeking to specific positions, and reading portions of a file.