问题
My first time ever trying to traverse directories, but stat
is throwing errors for some of the directories due to what seems to be a lack of permission.
Error: EPERM: operation not permitted, stat 'K:\System Volume Information'
I'd like to simply avoid calling stat
on a given directory in the first place if it is going to throw an error, yet I can't figure out how to do it.
I've tried looking into ignoring protected directories altogether. However, all of the questions I came across used regular expressions that – to my limited knowledge of MacOS, Linux, and how things are handled under the hood on Windows – didn't seem to be applicable to the Windows environment.
I've tried checking the read and write permissions of the directory before making any call to stat
, but this doesn't seem to do anything?
async function scanDirs(){
const
r = await fsp.readFile('./config.json', 'utf8'),
archives = JSON.parse(r).archives,
fs = require('fs'),
{ join } = require('path'),
traverse = async (dir) => {
try {
const perm = await fsp.access(dir, fs.constants.R_OK)
if (perm === undefined){
const stats = await fsp.stat(dir)
if (stats.isDirectory()){
const subfolders = await fsp.readdir(dir)
subfolders.forEach(path => {
const fullPath = join(dir, path)
traverse( fullPath )
})
}
}
}
catch (error){
console.error(error)
}
}
for (const dir of archives){
traverse(dir)
}
}
I've also just tried checking the permissions of a given folder's children before feeding them back into traverse
, but this doesn't work either.
for (const path of subfolders){
const
fullPath = join(dir, path),
perm = await fsp.access(fullPath, fs.constants.R_OK)
if (perm === undefined) traverse(fullPath)
}
Any help would be appreciated.
来源:https://stackoverflow.com/questions/58619990/check-permission-before-stat-method-to-avoid-errors