denoland / deno

A modern runtime for JavaScript and TypeScript.
https://deno.com
MIT License
94.04k stars 5.23k forks source link

nodejs `fs.access()` for Deno? #10021

Closed Mehuge closed 3 years ago

Mehuge commented 3 years ago

https://nodejs.org/api/fs.html#fs_fspromises_access_path_mode

Unless I am missing something, Deno doesn't currently support access(file, mode) yet does support chmod(file, mode).

It's use case is more for compatibility than anything else. Can handle lack of permissions by catching the exception thrown. I only came across it because I am converting code from nodjs to deno, and it uses access() to check if it has permission to read or write to a file before attempting to read or write to that file.

lucacasonato commented 3 years ago

Instead of check then act, just try to act, and if it fails catch possible permission errors when you act. Otherwise you are vulnerable to a TOCTOU race condition where the file permissions change between check and action.

You can just Deno.open the file. If opening fails due to a permission error it will throw a Deno.errors.PermissionDenied. If the file opens successfully you can read and write to it as usual.

See also the comment in the node docs:

Using fsPromises.access() to check for the accessibility of a file before calling fsPromises.open() is not recommended. Doing so introduces a race condition, since other processes may change the file's state between the two calls. Instead, user code should open/read/write the file directly and handle the error raised if the file is not accessible.

If you really want this behaviour you can just Deno.open and then immediately close the returned file.

stale[bot] commented 3 years ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed in 7 days if no further activity occurs. Thank you for your contributions.