我正在使用 Node 14.5 和文件系统 api 执行一些基本的 readdir 操作和文件/目录读取操作...
我只是想知道,当我得到一个描述文件/目录的“Dirent”对象时,当我迭代它的属性时,我可以看到一个带有数字值的“[Symbol(type)]”属性,这可能是该文件的类型..但是我无法以任何方式访问该属性...
Dirent {
name: 'Some name of file.mp4',
[Symbol(type)]: 1
}
我现在的问题是:这种属性是什么?我如何访问它?或者我怎样才能创建这样的属性以及为什么它会出现?我知道我可以使用 isDirectory() 等方法,但我只是想知道该属性是什么......
这是我的代码:
const fs = require('fs');
const path = require('path');
const walkDirs = async (dir_path, isSubdir = false, round = 0) => {
try {
const files = await fs.promises.readdir(dir_path);
const dirs = fs.opendirSync(dir_path);
// console.log(dirs);
for await (const dirent of dirs) {
for ( let prop in dirent) {
console.log("prop:", prop, dirent[prop]);
}
}
} catch(error) {
console.log("Error catched: ", error);
}
}
walkDirs("D:/", false, 0);
最佳答案
如果您转到fs module's source code for the DirEnt
class ,你会发现这个:
class Dirent {
constructor(name, type) {
this.name = name;
this[kType] = type;
}
isDirectory() {
return this[kType] === UV_DIRENT_DIR;
}
isFile() {
return this[kType] === UV_DIRENT_FILE;
}
isBlockDevice() {
return this[kType] === UV_DIRENT_BLOCK;
}
isCharacterDevice() {
return this[kType] === UV_DIRENT_CHAR;
}
isSymbolicLink() {
return this[kType] === UV_DIRENT_LINK;
}
isFIFO() {
return this[kType] === UV_DIRENT_FIFO;
}
isSocket() {
return this[kType] === UV_DIRENT_SOCKET;
}
}
如果您随后查找kType
,您会发现:
const kType = Symbol('type');
并且,该代码中的所有值(例如 UV_DIRECT_DIR
和 UV_DIRENT_FILE
)都是从 libuv 导入的常量,用于描述目录条目的类型。
因此,您所询问的属性似乎包含目录条目的 libuv 类型,并且他们使用符号作为属性名称,因为他们不打算公开使用或记录该内部实现细节。
如果你不知道libuv是什么,它是nodejs用来访问操作系统服务的跨平台库。它将一些操作系统细节抽象为一个通用接口(interface),以允许更多的nodejs代码一次编写并在多个平台(Win/Mac/Unix)上工作。
上面提到的底层 UV 常数定义为 here在 uv.h
的 libuv 中的 C++ 代码中。
typedef enum {
UV_DIRENT_UNKNOWN,
UV_DIRENT_FILE,
UV_DIRENT_DIR,
UV_DIRENT_LINK,
UV_DIRENT_FIFO,
UV_DIRENT_SOCKET,
UV_DIRENT_CHAR,
UV_DIRENT_BLOCK
} uv_dirent_type_t;
关于node.js - Nodejs 14.5 文件系统 API Dirent "Symbol(type)"属性是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62837749/