Search code examples
crystal-lang

In Crystal, how can you tell if a file is text or binary?


If you have 2 files, one text and the other binary, is it possible to determine which is a text file and which is a binary using Crystal?


Solution

  • I suppose, it's impossible, using native Crystal. To determine type of a file, it needs to read a part of a file and guess its type on the content basis. This can be a tricky part, so if you need a relatively reliable solution, I'd suggest invoke file --mime-type -b <file> from Crystal and parse the output, though it makes mistakes sometimes too.

    Additionally you can use crystal-mime shard to handle the output of file command.