节点 JS - 没有这样的文件?

Node JS - No such file?

我正在使用这段代码按需删除文件

{
...
    fs.access(path, (err)=> err || fs.unlink(path));    
...
}

我遇到了这个错误

Error: ENOENT: no such file or directory, unlink 'C:\ ... ' at Error (native)

这对我来说毫无意义,因为我实际上只是在尝试取消链接之前检查文件是否存在 - 我感觉幕后发生了一些奇怪的事情,比如文件锁定。

如何纠正这个错误?

此外,我是否需要在尝试删除之前自行锁定文件,以保证可靠和安全的删除。每次用户尝试删除他们的文件时,我都不会在那里手动删除文件并重新启动服务器。

不建议在写入或删除之前调用 fs.access。请检查以下 link https://nodejs.org/api/fs.html#fs_fs_access_path_mode_callback

Using fs.access() to check for the accessibility of a file before calling fs.open(), fs.readFile() or fs.writeFile() 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.