Execing Processes in PureScript
Here’s the translation of the Go code to PureScript, with explanations in Markdown format suitable for Hugo:
Our example demonstrates how to execute external processes in PureScript, replacing the current process with another one. This is similar to the classic exec
function in Unix-like operating systems.
module Main where
import Prelude
import Effect (Effect)
import Effect.Console (log)
import Node.ChildProcess (spawn)
import Node.Process (exit)
import Node.Buffer (toString)
import Node.Encoding (Encoding(..))
main :: Effect Unit
main = do
-- For our example, we'll exec 'ls'. In PureScript, we don't need to find
-- the absolute path as Node.js will handle this for us.
let binary = "ls"
-- We'll give 'ls' a few common arguments.
-- Note that in PureScript, we don't need to include the program name as the first argument.
let args = ["-a", "-l", "-h"]
-- Spawn the process
process <- spawn binary args {}
-- Handle the output
process.stdout.on "data" \data -> do
output <- toString UTF8 data
log output
-- Handle the process exit
process.on "exit" \code -> do
log $ "Process exited with code " <> show code
exit 0
In PureScript, we use the Node.ChildProcess
module to spawn external processes. Unlike Go’s syscall.Exec
, this doesn’t completely replace the current process, but it allows us to run external commands and capture their output.
When we run our program, it will execute ls
with the specified arguments and print the output:
$ spago run
total 24K
drwxr-xr-x 4 user user 4.0K Jun 10 12:00 .
drwxr-xr-x 20 user user 4.0K Jun 10 11:55 ..
-rw-r--r-- 1 user user 498 Jun 10 12:00 Main.purs
-rw-r--r-- 1 user user 229 Jun 10 11:55 packages.dhall
-rw-r--r-- 1 user user 145 Jun 10 11:55 spago.dhall
Process exited with code 0
Note that PureScript, being primarily a functional language, handles process execution differently from Go. Instead of directly replacing the current process, we spawn a child process and handle its output and exit code. This approach provides more flexibility in terms of input/output handling and error management.
PureScript doesn’t offer a direct equivalent to Unix’s fork
function. However, for most use cases, PureScript’s approach of using Node.js’s child process functionality, combined with its powerful concurrency abstractions (like Aff
for asynchronous effects), covers a wide range of scenarios where you might use fork
in other languages.