如何 return 来自 fs.accessAsync 的值

how to return a value from fs.accessAsync

我正在尝试检查是否是特定文件。文件夹或目录是否可以读取。我使用了下面发布的代码。代码有效,但我想 了解以下内容:

1- 什么时候打印错误信息?例如,文件不存在时会打印吗?我尝试了一个不存在的文件,但错误消息是 从未打印过。

2- 如何从 fs.accessSync() 中 return 一个值?例如,如果文件可以读取,我会 return 1,如果不是,我会 return 0。 如代码所示,我尝试 return 1,但随后控制台打印 "undefined".

请回答问题

代码:

const d = fs.accessSync(path, fs.constants.R_OK, (err) => {
if (err) {
console.log('is not readable is readable________________');
}

return 1;
});

console.log(d);

根据 nodejs 文档,fs.accessSync 不支持回调,您必须为此使用 try catch

try {
  fs.accessSync('etc/passwd', fs.constants.R_OK | fs.constants.W_OK);
  console.log('can read/write');
} catch (err) {
  console.error('no access!');
}

问题是您正试图将 accessSync 当作异步方法来使用。

fs.access 有一个异步方法和一个同步方法:

同步方法 - https://nodejs.org/api/fs.html#fs_fs_accesssync_path_mode

这就是您应该使用的方式 accessSync

const checkPermissions = file => {
  try {
    fs.accessSync(file, fs.constants.R_OK);
    console.log('can read/write');
    return true;
  } catch (err) {
    console.error('is not readable is readable________________');
    return false;
  }
};

if (checkPermissions('./some/location/file.pdf')) {
  console.log('I have permissions to the file');
} else {
  console.error('I do NOT have permissions to the file');
}

异步方法 - https://nodejs.org/api/fs.html#fs_fs_access_path_mode_callback

回调是作为参数传递给函数以供稍后执行的方法。这是 node.js 的核心部分,我强烈建议您继续阅读。节点社区一直在转向 promises,现在 async/await 但了解回调如何工作以真正理解 promises 或 async/await 的新语法仍然很重要(在我看来)。