📌  相关文章
📜  来自 fs.Stats 类的 Node.js stats.nlink 属性

📅  最后修改于: 2022-05-13 01:56:48.320000             🧑  作者: Mango

来自 fs.Stats 类的 Node.js stats.nlink 属性

stats.nlink 属性是 fs.Stats 类的内置应用程序编程接口,用于获取文件的硬链接数。

句法:

stats.nlink;

返回值:它返回一个数字或 BigInt 值,表示文件的硬链接数。

以下示例说明了 Node.js 中 stats.nlink 属性的使用:

示例 1:

// Node.js program to demonstrate the   
// stats.nlink property
  
// Accessing fs module
const fs = require('fs');
  
// Calling fs.Stats stats.nlink for 
// files using stat
fs.stat('./filename.txt', (err, stats) => {
  if (err) throw err;
  console.log("using stat: number of "
    + "hard-links for the file is "
    + stats.nlink);
});
   
// Using lstat
fs.lstat('./filename.txt', (err, stats) => {
  if (err) throw err;
  console.log("using lstat: number of "
    + "hard-links for the file is "
    + stats.nlink);
});
  
// For directories
// Using stat
fs.stat('./', (err, stats) => {
  if (err) throw err;
  console.log("using stat: number of "
    + "hard-links for the file is "
    + stats.nlink);
});
   
// Using lstat
fs.lstat('./', (err, stats) => {
  if (err) throw err;
  console.log("using lstat: number of "
    + "hard-links for the file is "
    + stats.nlink);
});

输出:

using stat: number of hard-links for the file is  1
using lstat: number of hard-links for the file is  1
using stat: number of hard-links for the file is  1
using lstat: number of hard-links for the file is  1

示例 2:

// Node.js program to demonstrate the   
// stats.nlink property
  
// Accessing fs module
const fs = require('fs').promises;
  
// Calling fs.Stats stats.nlink
(async () => {
    const stats = await fs.stat('./filename.txt');
    console.log("using stat synchronous: number "
        + "of hard-links for the file is "
        + stats.nlink);
})().catch(console.error)

输出:

(node:13780) ExperimentalWarning: The fs.promises API 
is experimental 
using stat synchronous: number of hard-links for the file is 1

注意:以上程序将通过使用node filename.js命令编译运行,并正确使用 file_path。

参考: https://nodejs.org/api/fs.html#fs_stats_nlink