Node.js 文件统计
【Node.js file stats】
每个文件都有一组我们可以使用 Node.js 检查的详细信息。特别是,可以使用 fs 模块 提供的 stat() 方法。
【Every file comes with a set of details that we can inspect using Node.js. In particular, using the stat() method provided by the fs module.】
你称之为传递文件路径,一旦 Node.js 获取到文件详细信息,它将调用你传递的回调函数,该函数有两个参数:一个错误信息和文件统计信息:
【You call it passing a file path, and once Node.js gets the file details it will call the callback function you pass, with 2 parameters: an error message, and the file stats:】
const = ('node:fs');
.('/Users/joe/test.txt', (, ) => {
if () {
.();
}
// we have access to the file stats in `stats`
});
Node.js 还提供了一种同步方法,它会阻止线程,直到文件统计信息准备就绪:
【Node.js also provides a sync method, which blocks the thread until the file stats are ready:】
const = ('node:fs');
try {
const = .('/Users/joe/test.txt');
} catch () {
.();
}
文件信息包含在 stats 变量中。我们可以使用 stats 提取哪些类型的信息?
【The file information is included in the stats variable. What kind of information can we extract using the stats?】
很多,包括:
- 如果文件是目录还是文件,可以使用
stats.isFile()和stats.isDirectory() - 如果文件是符号链接,可以使用
stats.isSymbolicLink() - 使用
stats.size获取文件大小(以字节为单位)。
还有其他高级方法,但你在日常编程中将使用的大部分方法都是这种方法。
【There are other advanced methods, but the bulk of what you'll use in your day-to-day programming is this.】
const = ('node:fs');
.('/Users/joe/test.txt', (, ) => {
if () {
.();
return;
}
.(); // true
.(); // false
.(); // false
.(.); // 1024000 //= 1MB
});
如果你愿意,你也可以使用 fs/promises 模块提供的基于 Promise 的 fsPromises.stat() 方法:
【You can also use promise-based fsPromises.stat() method offered by the fs/promises module if you like:】
const = ('node:fs/promises');
async function () {
try {
const = await .('/Users/joe/test.txt');
.(); // true
.(); // false
.(); // false
.(.); // 1024000 //= 1MB
} catch () {
.();
}
}
();
你可以在官方文档中阅读有关 fs 模块的更多信息。
【You can read more about the fs module in the official documentation.】