bcpeinhardt / simplifile

Simple file operations for Gleam that work on all targets (Erlang/Node/Deno)
71 stars 10 forks source link

πŸ› `simplifile.delete` logs a runtime error on the js target. #14

Closed hayleigh-dot-dev closed 11 months ago

hayleigh-dot-dev commented 11 months ago

I have some code that attempts to delete a directory if it exists but doesn't care if the operation fails.

// Every build will generate a clean directory. Any files that already exist
// will be wiped, and any previously-generated routes will also be deleted and
// regenerated.
let _ = simplifile.delete(out_dir)

When this code runs on a project where out_dir doesnt exist, node throws a runtime error:

Error: ENOENT: no such file or directory, unlink 'priv'
    at Object.unlinkSync (node:fs:1773:3)
    at deleteFileOrDirRecursive (file:///Users/hayleigh/work/lustre-labs/lustre-labs.github.io/build/dev/javascript/simplifile/simplifile_js.mjs:69:16)
    at Module.delete$ (file:///Users/hayleigh/work/lustre-labs/lustre-labs.github.io/build/dev/javascript/simplifile/simplifile.mjs:278:15)
    at Module.build (file:///Users/hayleigh/work/lustre-labs/lustre-labs.github.io/build/dev/javascript/lustre_ssg/lustre/ssg.mjs:191:23)
    at main (file:///Users/hayleigh/work/lustre-labs/lustre-labs.github.io/build/dev/javascript/app/build.mjs:92:15)
    at file:///Users/hayleigh/work/lustre-labs/lustre-labs.github.io/build/dev/javascript/app/gleam.main.mjs:2:1
    at ModuleJob.run (node:internal/modules/esm/module_job:194:25) {
  errno: -2,
  syscall: 'unlink',
  code: 'ENOENT',
  path: 'priv'
}

It looks like you have a stray console.log that probably should have been removed before release :)

export function deleteFileOrDirRecursive(fileOrDirPath) {
    try {
        if (isDirectory(fileOrDirPath)) {
            fs.rmdirSync(path.normalize(fileOrDirPath), { recursive: true })
        } else {
            fs.unlinkSync(path.normalize(fileOrDirPath))
        }
        return new Ok(undefined)
    } catch (e) {
        console.log(e) //<-- πŸ‘€
        return new GError(stringifyError(e))
    }
}
bcpeinhardt commented 11 months ago

Whoops, I've got to start doing proper debugging. I'll get this fixed asap :)

bcpeinhardt commented 11 months ago

Fixed with latest publish (v0.1.14) :) I also added a function delete_all which takes a list of paths to delete. It specifically ignores an enoent (no such file or directory) error, so instead of let _ = simplifile.delete(out_dir) you can call let res = simplifile.delete_all([out_dir]) and handle the error if there is one (for example, a permission error).