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

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

fs.Stats 类的 Node.js stats.mode 属性

stats.mode 属性是 fs.Stats 类的内置应用程序编程接口,用于获取文件类型和模式作为位字段。

句法:

stats.mode;

返回值:它返回一个数字或 BigInt 值,表示描述文件类型和模式的位域。

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

示例 1:

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

输出:

using stat: the type and mode bit-field of the file is  33206
using lstat: the type and mode bit-field of the file is  33206
using stat: the type and mode bit-field of the file is  16822
using lstat: the type and mode bit-field of the file is  16822

示例 2:

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

输出:

(node:9448) ExperimentalWarning: The fs.promises API
is experimental 
using stat synchronous: the type and mode bit-field 
of the file is  33206

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

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