Environment Variables in PureScript
Environment variables are a universal mechanism for conveying configuration information to Unix programs. Let’s look at how to set, get, and list environment variables in PureScript.
module Main where
import Prelude
import Effect (Effect)
import Effect.Console (log)
import Node.Process (lookupEnv, setEnv)
import Data.Maybe (Maybe(..))
import Node.Process as Process
main :: Effect Unit
main = do
-- To set a key/value pair, use `setEnv`. To get a
-- value for a key, use `lookupEnv`. This will return
-- Nothing if the key isn't present in the environment.
setEnv "FOO" "1"
foo <- lookupEnv "FOO"
bar <- lookupEnv "BAR"
log $ "FOO: " <> show foo
log $ "BAR: " <> show bar
-- Use `Process.getEnv` to list all key/value pairs in the
-- environment. This returns a record of strings.
-- Here we print all the keys.
log ""
env <- Process.getEnv
let keys = Object.keys env
traverse_ log keys
Running the program shows that we pick up the value for FOO
that we set in the program, but that BAR
is empty.
$ spago run
FOO: (Just "1")
BAR: Nothing
The list of keys in the environment will depend on your particular machine.
PATH
SHELL
...
FOO
If we set BAR
in the environment first, the running program picks that value up.
$ BAR=2 spago run
FOO: (Just "1")
BAR: (Just "2")
...
In PureScript, we use the Node.Process
module to interact with environment variables. The lookupEnv
function returns a Maybe String
, which we handle using pattern matching or the show
function for simplicity in this example. The setEnv
function is used to set environment variables.
Instead of os.Environ()
, we use Process.getEnv
which returns a record of key-value pairs. We then use Object.keys
to get all the keys from this record.
Note that in PureScript, we’re working in a more functional style, using Effect
for side effects and Maybe
for potentially missing values.