Subject: Initializing file I/O so that code is agnostic to running locally/on cloud

For non-log files it probably depends on the data you want to write or read.

For example, if you want to read toml, json, csv files, there are delicate packages for that.
Typically these packages can deal with IO streams.

For example, if you have a toml file, you could use TOML · The Julia Language which works with IO streams as input.

using TOML
io = open("config.toml")
data = TOML.parse(io)
close(io)

So, you might define your own function open_resource(...) which opens the right IO stream on demand.

function open_resource(fn)
   if ENV["STAGE"] == "Development"
        return open(fn)
    elseif ENV["STAGE"] == "Production"
        return # ... your code for another context
    end
end

However, a better syntax might be to support the open do ... approach (which closes files automatically)

open("config.toml") do f 
   data = TOML.pares(io)
end

(See Networking and Streams · The Julia Language )

If you want to support this you could do

function open_resource(f::Function, fn)
   io = open_resource(fn)
   f(io)
   close(io)
end

then the example above becomes

open_resource("config.toml") do f 
   data = TOML.pares(io)
end

I didn’t run the code, sorry if there are typos…

1 Like