Term formats
A program that keeps settings or state between runs writes a file, and Erlang has two formats for it. A config file is a sequence of Erlang terms that a human can read and edit, which file:consult/1 parses. A state file is a term in the external format, which term_to_binary/1 writes and binary_to_term/2 reads. This lesson writes, reads and breaks both.
A config file
A term file holds one term per entry, each ending with a period. An operator can open it in an editor and write a list of options. file:consult/1 answers {ok, Terms}, where each term is one entry, and io_lib:format("~p.~n", [Term]) writes a term back in the same form:
settings.config
{server, [{port, 8080}, {host, "localhost"}]}.
settings.erl
-module(settings). -export([main/0]). main() -> Text = "{server, [{port, 8080}, {host, \"localhost\"}]}.\n", ok = file:write_file("settings.config", Text), {ok, [{server, Options}]} = file:consult("settings.config"), io:format("~p~n", [proplists:get_value(port, Options)]), io:format("~s~n", [io_lib:format("~p.~n", [{server, Options}])]).
erlc settings.erl
erl -noshell -eval 'settings:main(), halt().'
8080 {server,[{port,8080},{host,"localhost"}]}.
The program writes the file first so the lesson runs on its own; a real program reads a file the operator wrote and never needs to create it. The term comes back as the composition of tuples, lists and strings it was, with no parser of a custom syntax to maintain. The keywords lesson reads the options list that the config returns.
A state file
A state file is not for a human. term_to_binary/1 writes the exact term and binary_to_term/2 reads it back; the safe option refuses atoms the node does not already have, which is the right default for a file that another program may have written:
state.erl
-module(state). -export([main/0]). main() -> ok = file:write_file("state.bin", term_to_binary(#{count => 2})), {ok, Bin} = file:read_file("state.bin"), io:format("~p~n", [binary_to_term(Bin, [safe])]).
erlc state.erl
erl -noshell -eval 'state:main(), halt().'
#{count => 2}
The file is small, exact and fast to read, and it keeps the Erlang types: an atom stays an atom, a tuple stays a tuple. It is not portable to another language, and it must not be read with the default options from an untrusted source. The JSON format is the portable alternative for a value that leaves the cluster, and the JSON lesson shows it.
A broken file
file:consult/1 does not raise on a syntax error: it answers {error, {Line, Module, Reason}}, and the line points at the token that ended the term too early. A program that matches only {ok, Terms} crashes with a badmatch on a file that an operator edited by hand, which is the normal life of a config file:
broken.erl
-module(broken). -export([main/0]). main() -> ok = file:write_file("broken.config", "{server, [}.\n"), Result = case file:consult("broken.config") of {ok, _Terms} -> parsed; {error, _Reason} -> no_terms end, io:format("~p~n", [Result]).
erlc broken.erl
erl -noshell -eval 'broken:main(), halt().'
no_terms
The program keeps the reason out of the print on purpose; a real one writes it to the log with the file name, so the operator knows which line to fix. A term file is input, and every input is matched, not trusted.
Which file for what
A config file is for values a human sets: a port, a host, a list of features. It is
read at start, it survives an upgrade because the syntax is the language, and it is
safe to show in a ticket. A state file is for values the program writes: a sequence
number, a cache, the last position of a reader. It is exact and fast, and it is not
edited. A database or ETS is for the values
that change while the program runs.
Both formats belong to one release of one program. A term written by an old version is
read by the new one only if the shape did not change; a version field in the term is
the cheap way to say which shape it is.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
file:consult/1answer for a valid term file?Answer
{ok, Terms}It parses every term and answers them in a list under the
oktag. -
What ends every term of a consulted file?
Answer
A full stop
The file is a sequence of Erlang forms, and each form ends with a full stop.
-
What does
file:consult/1answer for a syntax error?Answer
{error, {Line, Module, Reason}}The parse error is a value with the line and the parser reason, not an exception.
-
Why read a state file with
[safe]?Answer
It refuses atoms the node does not already have
An untrusted binary must not be allowed to create atoms in the never-shrinking atom table.
-
What does this module print?
-module(q1). -export([main/0]). main() -> ok = file:write_file("c.config", "{port, 8080}.\n"), {ok, [{port, Port}]} = file:consult("c.config"), io:format("~p~n", [Port]).Answer
8080The file holds one tuple, and the match binds its second element.
-
What does this module print?
-module(q2). -export([main/0]). main() -> ok = file:write_file("s.bin", term_to_binary({count, 2})), {ok, Bin} = file:read_file("s.bin"), io:format("~p~n", [binary_to_term(Bin, [safe])]).Answer
{count,2}The binary round-trips the term, and its atoms already exist in the node.
-
What does this module print?
-module(q3). -export([main/0]). main() -> ok = file:write_file("c.config", "{port, 8080}.\n"), {ok, Terms} = file:consult("c.config"), io:format("~p~n", [length(Terms)]).Answer
1A consult answers one list element per term, and the file holds one term.
-
What does this module print?
-module(q4). -export([main/0]). main() -> io:format("~s~n", [io_lib:format("~p.~n", [{port, 8080}])]).Answer
{port,8080}.~pwrites the term and the format adds the full stop that a consult expects. -
Which file is the right place for a value a human edits?
Answer
A config file read by
file:consult/1A term file keeps the language syntax, so an operator can read and change it.
-
Which file is the right place for a sequence number the program writes?
Answer
A state file of
term_to_binaryThe state file is exact and fast, and nobody edits it by hand.
The examples on this page were compiled and run with Erlang/OTP 27 (erts-15.2.7.14) on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Автор статьи: Arthur Isaev