Command Line Arguments in PureScript
Command-line arguments are a common way to parameterize execution of programs. For example, pulp run src/Main.purs
uses run
and src/Main.purs
arguments to the pulp
program.
module Main where
import Prelude
import Effect (Effect)
import Effect.Console (log)
import Node.Process (argv)
main :: Effect Unit
main = do
-- `argv` provides access to raw command-line arguments.
-- Note that the first two values in this array are the
-- Node.js executable path and the script path, and
-- `drop 2 argv` holds the arguments to the program.
args <- argv
let argsWithProg = args
let argsWithoutProg = drop 2 args
-- You can get individual args with normal indexing.
let arg = args !! 3
log $ show argsWithProg
log $ show argsWithoutProg
log $ show arg
To experiment with command-line arguments, it’s best to compile the program first:
$ pulp build
$ node output/Main.js a b c d
[ 'path/to/node', 'output/Main.js', 'a', 'b', 'c', 'd' ]
[ 'a', 'b', 'c', 'd' ]
(Just "c")
In PureScript, we use the argv
function from the Node.Process
module to access command-line arguments. The drop 2
function is used to remove the first two elements (Node.js executable path and script path) from the argument list.
Note that in PureScript, array indexing with !!
returns a Maybe
type, so the output for the individual argument is wrapped in Just
.
Next, we’ll look at more advanced command-line processing with options parsing libraries in PureScript.