Fix: Check output file isn't already a directory, handle errors, fix and add tests

Fixes #1034.
Why not use `file.existsSync()` to avoid the error?