sindresorhus / trash

Move files and directories to the trash
MIT License
2.58k stars 79 forks source link

How to tell whether deletion succeeded? #94

Open whyboris opened 4 years ago

whyboris commented 4 years ago

README claims trash() returns a Promise, but the expected type is void? https://github.com/sindresorhus/trash/blob/bdfbd071e491df63c2e59bb4d72ebfac6c60ef10/index.test-d.ts#L4

So there is currently no way to tell whether the library succeeded in moving a file into the trash or whether it encountered an error?

trash('some-file.lol')
  .then((result) => {
    console.log(result); // always `undefined`
  })
  .catch((err) => {
    console.log(err); // never runs
  });

So, the library just sends a command to the OS and doesn't know what happens after?

When you tell the library to delete a non-existing file, it behaves the same way (no error, no notification).

This isn't a problem -- it's just that I'd love to have my app respond appropriately, not just assume that deletion occurred correctly 😓

I can manually get node to check whether the file is present to confirm it was deleted, but would be great if I didn't have to 😅

Please let me know if I'm misunderstanding something.

sindresorhus commented 4 years ago

It doesn't reject the promise if you give it an non-existent file as the input is a glob pattern, not a file path. So if running the glob patterns results in zero files, that might be expected or it might not. It's not for us to decide. We could try to detect whether the input is an actual file path or a glob, and if it's a file path and it doesn't exist, we could throw, but that is not easy to get right. We could maybe add a glob: false option where it would then fail loudly if some of the given file paths don't exist.

However, it does reject the promise if something wrong happened while moving the files to the trash.

The behavior should be better documented regardless though.

whyboris commented 4 years ago

Thank you for the quick response. I handled it like this for my purposes (I'm only deleting 1 file at a time) 😁

  (async () => {
    await trash(fileToDelete);

    fs.access(fileToDelete, fs.F_OK, (err: any) => {
      if (err) {
        // my logic for handling a successful delete 
      }
    });

  })();