Basic Directory Display in YAWS/Erlang

When setting up a web server for the first time what I always want to do is get a script working that just does basic things like show the contents of the directory on the server.  It helps me orient myself to the new language/software.

Here’s my version of the Erlang code block that you can slot into any .yaws page which will show what’s going on and introduce you to a few of the ways that YAWS/Erlang do things.

out(Arg) ->
% change directory to the document root of the webserver
% determining YAWS' current working directory
% usually where you were when you typed sudo yaws
% not normally the same as the document root
CurrentDir = element(2,file:get_cwd()),
% pull up a directory listing
DirList = element(2,file:list_dir(CurrentDir)),
% define a function for our filter
IsDir = fun(F) -> filelib:is_dir(F) end,
% filter out all the directories
AllDirs = lists:filter(IsDir,DirList),
% make directories into links using a mapping function
ConvertToLink = fun(D) ->
"<a href=\"" ++ D ++ "\">" ++ D ++ "</a>" end,
LinkedDirs = lists:map(ConvertToLink,AllDirs),
% define a filter function and use it to
% filter out all the regular files
IsReg = fun(F) -> filelib:is_regular(F) end,
AllRegs = lists:filter(IsReg,DirList),
% HTML-ify the two lists ready for output
DirBlock = string:join(LinkedDirs,"</li>\n<li>"),
RegBlock = string:join(AllRegs,"</li>\n<li>"),
% send output back to the browser
"<h1>" ++ CurrentDir ++ "</h1>\n" ++
"<h2>Directories</h2>\n" ++
"<ul>\n<li>" ++ DirBlock ++ "</li>\n</ul>\n" ++
"<h2>Regular Files</h2>\n" ++
"<ul>\n<li>" ++ RegBlock ++ "</li>\n</ul>\n"

(code block available from

It’s not meant to be comprehensive, or even very functional.  It certainly won’t win any Erlang ‘elegance’ prizes — it probably would be considered long-winded and inefficient by most proficient Erlang programmers.

That misses the point.

If you’re new to Erlang/YAWS life is likely to get really confusing really fast.  You may just have spent two hours slamming your head into a brick wall trying to get something done which you consider to be trivial in another language… and just want some concrete examples instead of references to man pages and obscure code snippets.

Hopefully the above will help.

PS:  While the above code turns the directories into links that you can click, YAWS will not let you enter those directories by default.  You need to edit your yaws.conf file, find the <server> block and add:

dir_listings = true

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s