javascript - 遍历我的主目录时出现 EPERM 错误的原因是什么?

标签 javascript node.js macos recursion runtime-error

我用谷歌搜索

EPERM: operation not permitted

我在 npm 问题和这个错误上得到了很多点击。

这不是我的情况(不是重复的),因为我没有运行 npm,我正在运行我自己的 Node 代码。

我收到此错误:

错误

{ 
  Error: 'EPERM: operation not permitted',
  errno: -1,
  code: 'EPERM',
  syscall: 'scandir',
  path: '../../../Library/Application Support/CallHistoryDB/' 
};

在我的主目录上运行下面的代码时。

我使用两者来运行它

node getInfo

sudo node getInfo

但我遇到了同样的错误。

如果我在本地存储库上运行此代码,则它可以正常工作,但是当我尝试遍历整个主目录时,我会收到错误。

执行的代码:

// Libraries
const fs = require('fs');
const h = require('./helper');

// Start recursing here
const start = '../../../';

// API
getThings(start).then(() => {
  console.log(data);
}).catch(h.error)

// Accesses the file system and returns an array of files / folders
async function getThings (folder) { 
  const things = await fs.promises.readdir(folder);
  for(let i = 0; i < things.length; i++) {
    await getStats(things[i], folder);
  }
}

// Gets statistics for each file/folder
async function getStats (thing, folder) {
  const path = folder + thing;
  const stats = await fs.promises.stat(path);
  await checkForFolder(stats, thing, path); 
}

// if the file/folder is a folder, recurse and do it again
async function checkForFolder(stats, thing, path){
  // logThing(stats, thing, path);
  if (stats.isDirectory() ) {
    await getThings(path + '/');
  }
}

研究

SO - EPERM vs EACCES

最佳答案

'../../../Library/Application Support/CallHistoryDB/' 

此路径受 macOS 安全设置保护,因为它可能包含敏感的电话历史记录数据。

如果您特别需要在 Node 应用程序中访问它,则需要在系统偏好设置中为用于运行此脚本的应用程序(例如 Terminal.app、iTerm 或 IDE)启用完全磁盘访问, 如下所示。请注意,这将使您在终端中运行的所有应用程序都可以访问您的敏感个人文件;小心行事。

但是,如果您不需要专门访问此路径(而且您可能不应该),更好的解决方案可能是在每次调用 fs.promises.stat(path)< 时单独捕获错误。最简单的方法是将对 await fs.promises.stat(path) 的调用包装在 try … catch block 中,并打印或忽略错误。

enter image description here

关于javascript - 遍历我的主目录时出现 EPERM 错误的原因是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56203551/

相关文章:

javascript - 直接在 URL 中过滤 API 响应

node.js - 如何使用 express for Google 重定向不同的语言

node.js - SequelizeDatabaseError : SQLITE_ERROR: no such table: Users

macos - 如何通过命令行启动 growl

javascript - 邮政编码验证格式 nnnnn-nnnn

javascript - 从页面重定向时设置 "option"值 "select"

javascript - 有没有办法通过 jQuery 获取 CSS chop 文本?

node.js - lb-ng 环回命令从异步模块返回 "Cannot read property ' apply' of undefined"

python - 在 OS X 中使用 python 的 ctypes 调用 DLL

objective-c - 在 HTML5 文档中加载视频时,WebView 的自定义 NSURLProtocol 类不起作用