std.env
std.env reads and sets environment variables — the values the operating system or whoever starts the program gives it. It is the usual way to separate configuration from code.
std.env reads and sets environment variables — the values the operating system or whoever starts the program gives it. It is the usual way to separate configuration from code: a database path, a port value or a secret key that should not sit in the program itself.
Like everything else in Norscode, access is governed by capabilities. The program must have env.read to read the environment, and env.write to set a variable — otherwise the environment is unavailable, entirely on purpose, so that code you have not read cannot snoop on your secrets.
When to use it
Use std.env for configuration that should not sit in the code: a database path, a port, a secret key. hent reads a variable, finnes checks whether it is set, and sett sets one. Remember the env.read and env.write capabilities.
Getting started
bruk std.env som env
funksjon start() -> heiltall {
la port = env.hent("PORT")
hvis port == "" { port = "8080" } // sensible default
skriv("Bruker port " + port)
returner 0
}A common pattern is to read a variable and fall back on a default if it is not set. That way the same program can run differently in development and production without a code change.
The functions
Three small functions cover everything: hent reads, finnes checks, sett sets.
hent(nokkel: tekst) -> tekst— Reads an environment variable, or returns empty text if it is not set.finnes(nokkel: tekst) -> bool— True if the environment variable is set.sett(nokkel: tekst, verdi: tekst) -> tekst— Sets an environment variable for the running program.
Good to know
hentreturns an empty text when the variable is not set — combine it with a default value as the example shows.settaffects only the running program, not the system permanently.- Never put secrets in the code; read them from the environment, and give the program
env.readonly where it is needed.
std.env is one of the modules in the standard library. Everything ships with the runtime — no installation, no external dependencies. See also Documentation for the language and the runtime.
Related
- std.tekststd.tekst is the toolbox for everything to do with text — searching and checking, splitting and joining, trimming whitespace, changing case, and converting to and from numbers.
- std.httpstd.http is a client for talking to other services over HTTP and HTTPS. You can fetch data, send data, and interpret the response — including JSON — without building the request by hand.
- std.dbstd.db gives you access to databases with a small, familiar set of functions: open a connection, run SQL, fetch values and rows, and control transactions.