From 8f12a39c6e607fd6474414149a55f328777c7bbf Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Fri, 3 Aug 2018 00:51:26 -0500 Subject: [PATCH] Add Is This A Directory Or A File as a reason til --- README.md | 3 +- reason/is-this-a-directory-or-a-file.md | 38 +++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 reason/is-this-a-directory-or-a-file.md diff --git a/README.md b/README.md index af36aa8..85f4b39 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/). For a steady stream of TILs from a variety of rocketeers, checkout [til.hashrocket.com](https://til.hashrocket.com/). -_695 TILs and counting..._ +_696 TILs and counting..._ --- @@ -511,6 +511,7 @@ _695 TILs and counting..._ - [Generate Starter Reason Projects](reason/generate-starter-reason-projects.md) - [Helping The Compiler Help Us With Variants](reason/helping-the-compiler-help-us-with-variants.md) - [Inline Component Styles With Reason React](reason/inline-component-styles-with-reason-react.md) +- [Is This A Directory Or A File](reason/is-this-a-directory-or-a-file.md) - [Making Things Mutable](reason/making-things-mutable.md) - [Multi-Argument Functions As Syntactic Sugar](reason/multi-argument-functions-as-syntactic-sugar.md) - [Pattern Match On Exceptions](reason/pattern-match-on-exceptions.md) diff --git a/reason/is-this-a-directory-or-a-file.md b/reason/is-this-a-directory-or-a-file.md new file mode 100644 index 0000000..acc4c04 --- /dev/null +++ b/reason/is-this-a-directory-or-a-file.md @@ -0,0 +1,38 @@ +# Is This A Directory Or A File? + +When compiling [ReasonML](https://reasonml.github.io/) natively, we have access to a variety of +additional modules including the `Unix` module. We can interact with +directories and files using functions on `Unix`. + +```reason +let current_dir = Unix.opendir(Unix.getcwd()); +let first_file = Unix.readdir(current_dir); +/* is first_file a directory or a file? */ +Unix.closedir(current_dir); +``` + +Here we open the current working directory, grab the first thing out of that +directory -- maybe it's a file, maybe it's a directory, maybe it is +something else. Lastly, we close the directory. + +```reason +let current_dir = Unix.opendir(Unix.getcwd()); +let first_file = Unix.readdir(current_dir); + +switch(Unix.stat(first_file)) { +| Unix.stats({ st_kind: Unix.S_REG }) => print_endline("Regular File") +| Unix.stats({ st_kind: Unix.S_DIR }) => print_endline("Directory") +| Unix.stats({ st_kind: Unix.S_LINK }) => print_endline("Link") +| Unix.stats({ st_kind: Unix.S_SOCK }) => print_endline("Socket") +| _ => print_endline("Something else") +}; + +Unix.closedir(current_dir); +``` + +There are a variety of kinds of files to switch on. Here, we are switching +on _Regular Files_, _Directories_, _Links_, and _Sockets_. Everything else +falls through. + +See the [`Unix` module docs](https://reasonml.github.io/api/Unix.html) for +more details.