On this page

    🌐 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 fs = require('node:fs');
    
    fs.stat('/Users/joe/test.txt', (err, stats) => {
      if (err) {
        console.error(err);
      }
      // 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 fs = require('node:fs');
    
    try {
      const stats = fs.statSync('/Users/joe/test.txt');
    } catch (err) {
      console.error(err);
    }

    文件信息包含在 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 fs = require('node:fs');
    
    fs.stat('/Users/joe/test.txt', (err, stats) => {
      if (err) {
        console.error(err);
        return;
      }
    
      stats.isFile(); // true
      stats.isDirectory(); // false
      stats.isSymbolicLink(); // false
      console.log(stats.size); // 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 fs = require('node:fs/promises');
    
    async function example() {
      try {
        const stats = await fs.stat('/Users/joe/test.txt');
        stats.isFile(); // true
        stats.isDirectory(); // false
        stats.isSymbolicLink(); // false
        console.log(stats.size); // 1024000 //= 1MB
      } catch (err) {
        console.log(err);
      }
    }
    example();

    你可以在官方文档中阅读有关 fs 模块的更多信息。

    🌐 You can read more about the fs module in the official documentation.