How to use the stat function from fs

Find comprehensive JavaScript fs.stat code examples handpicked from public code repositorys.

fs.stat() is a Node.js method that returns information about a file, such as its size, ownership, and access permissions.

65
66
67
68
69
70
71
72
73
74
of the `fs.rename()` operation:

```js
fs.rename('/tmp/hello', '/tmp/world', (err) => {
  if (err) throw err;
  fs.stat('/tmp/world', (err, stats) => {
    if (err) throw err;
    console.log(`stats: ${JSON.stringify(stats)}`);
  });
});
fork icon209
star icon0
watch icon79

25
26
27
28
29
30
31
32
33
34
* fs.readFile(): 读取文件的内容。相关方法:fs.read()。
* fs.readlink(): 读取符号链接的值。
* fs.realpath(): 将相对的文件路径指针(.、..)解析为完整的路径。
* fs.rename(): 重命名文件或文件夹。
* fs.rmdir(): 删除文件夹。
* fs.stat(): 返回文件(通过传入的文件名指定)的状态。相关方法:fs.fstat()、fs.lstat()。
* fs.symlink(): 新建文件的符号链接。
* fs.truncate(): 将传递的文件名标识的文件截断为指定的长度。相关方法:fs.ftruncate()。
* fs.unlink(): 删除文件或符号链接。
* fs.unwatchFile(): 停止监视文件上的更改。
fork icon192
star icon570
watch icon16

+ 5 other calls in file

How does fs.stat work?

fs.stat() is a method provided by the Node.js fs module that returns an object containing information about a file. The information returned by fs.stat() includes the file's size, ownership, access permissions, and other metadata. Here's the syntax for fs.stat(): javascript Copy code {{{{{{{ fs.stat(path[, options], callback) path is the path to the file or directory you want to get information about. options is an optional object that can be used to specify additional options for the operation. callback is a function that will be called with two arguments: an error object (if there was an error) and the file information object. The file information object returned by fs.stat() includes the following properties: dev: the device ID of the file's filesystem. ino: the inode number of the file. mode: the file's permissions. nlink: the number of hard links to the file. uid: the file's owner ID. gid: the file's group ID. rdev: if the file is a special file (such as a device), this is the device ID of the file. size: the size of the file in bytes. blksize: the block size used by the file's filesystem. blocks: the number of blocks used by the file. Here's an example of how you might use fs.stat() to get information about a file: javascript Copy code {{{{{{{ class="!whitespace-pre hljs language-javascript">const fs = require('fs'); fs.stat('/path/to/file.txt', (err, stats) => { if (err) { console.error(err); return; } console.log(`File size: ${stats.size} bytes`); console.log(`Owner UID: ${stats.uid}`); console.log(`Group GID: ${stats.gid}`); console.log(`Permissions: ${stats.mode.toString(8)}`); }); In this example, we call fs.stat() with the path to a file (/path/to/file.txt). We pass a callback function that will be called with the file information object (stats) when the operation completes. In the callback, we log the file size, owner ID, group ID, and permissions to the console. The permissions are logged as an octal string, which can be converted to a human-readable format using tools like chmod or stat.

50
51
52
53
54
55
56
57
58
59

// .exists is still messed

exports.exists = function(path){
  return function(done){
    fs.stat(path, function(err, res){
      done(null, !err);
    });
  }
};
fork icon14
star icon106
watch icon8

108
109
110
111
112
113
114
115
116
117
const fs = require('fs/promises');

(async function(from, to) {
  try {
    await fs.rename(from, to);
    const stats = await fs.stat(to);
    console.log(`stats: ${JSON.stringify(stats)}`);
  } catch (error) {
    console.error('there was an error:', error.message);
  }
fork icon371
star icon0
watch icon78

+ 3 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
const fs = require("fs");

fs.stat("/path/to/file.txt", (err, stats) => {
  if (err) {
    console.error(err);
    return;
  }

  console.log(`File size: ${stats.size} bytes`);
  console.log(`Owner UID: ${stats.uid}`);
  console.log(`Group GID: ${stats.gid}`);
  console.log(`Permissions: ${stats.mode.toString(8)}`);
});

In this example, we're using fs.stat() to get information about a file located at /path/to/file.txt. We pass a callback function that will be called with two arguments: an error object (if there was an error), and a file information object (stats) containing information about the file. Within the callback, we first check whether an error occurred by checking whether err is truthy. If err is not null or undefined, we log the error message to the console using console.error() and return from the function to prevent any further processing. If there was no error, we log several pieces of information about the file to the console using console.log(). We access the file size using stats.size, the owner ID using stats.uid, the group ID using stats.gid, and the permissions using stats.mode.toString(8). The permissions are logged as an octal string, which can be converted to a human-readable format using tools like chmod or stat.

76
77
78
79
80
81
82
83
84
85
  assert.strictEqual(err.code, 'ENOENT');
  assert.strictEqual(err.syscall, 'stat');
  return true;
};

fs.stat(nonexistentFile, common.mustCall(validateError));

assert.throws(
  () => fs.statSync(nonexistentFile),
  validateError
fork icon42
star icon19
watch icon0

76
77
78
79
80
81
82
83
84
85
86
87
});


function testTruncate(cb) {
  fs.writeFile(filename, data, function(er) {
    if (er) return cb(er);
    fs.stat(filename, function(er, stat) {
      if (er) return cb(er);
      assert.equal(stat.size, 1024 * 16);


      fs.truncate(filename, 1024, function(er) {
fork icon9
star icon15
watch icon0

+ 5 other calls in file

1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489


const startApplication = async () => {
    // process license
    if (config.licensePath) {
        try {
            let stat = await fs.stat(config.licensePath);
            if (!stat.isFile()) {
                throw new Error(`Provided license key is not a regular file`);
            }
            const licenseFile = await fs.readFile(config.licensePath, 'utf-8');
fork icon113
star icon0
watch icon16

330
331
332
333
334
335
336
337
338
339
    return;
}else{
    
    if(err === null){
        
        fs.stat(chatsPath+dir_name+"/"+request.body.file_name+".jsonl", function(err, stat) {
            
            if (err === null) {
                
                if(stat !== undefined){
fork icon60
star icon276
watch icon17

+ 2 other calls in file

280
281
282
283
284
285
286
287
288
289
const runningUserName = process.env.USER;
exec('id -u ' + runningUserName, (err, stdout, stderr) => {
  if (stdout) {
    const runningUid = parseInt(stdout);
    if (!isNaN(runningUid)) {
      fs.stat('.', (err, stats) => {
        if (err) {
          return resolve(false);
        } else {
          const directoryUid = stats.uid;
fork icon5
star icon16
watch icon7

192
193
194
195
196
197
198
199
200
201
        else if (err.code === 'ENOENT')
            mkdirp(pathutil.dirname(path), mode, function (err) {
                return !err ? mkdirp(path, mode, done) : done(err);
            });
        else
            fs.stat(path, function (err, stat) {
                return err ? done(err) : !stat.isDirectory() ? done(new Error(path + ' is already a file')) : done(null);
            });
    });
}
fork icon3
star icon0
watch icon1

+ 5 other calls in file

1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
    }
})

if (!duplicate) {

    // fs.stat(options.href, (err, stats) => {

        // if (!err) {

            if (options.is_dir) {
fork icon2
star icon5
watch icon1

+ 3 other calls in file

31
32
33
34
35
36
37
38
39
40

// In the case of any other error, just see if there's a dir
// there already.  If so, then hooray!  If not, then something
// is borked.
default:
    fs.stat(p, function (er2, stat) {
        // if the stat fails, then that's super weird.
        // let the original error be the failure reason.
        if (er2 || !stat.isDirectory()) cb(er, made)
        else cb(null, made);
fork icon2
star icon1
watch icon2

474
475
476
477
478
479
480
481
482
483
static update_strategy(file) {
  try {
    if (Object.keys(MessageStrategy.watched_events).includes(strategies_dir + file) == false) {
      MessageStrategy.watched_events[strategies_dir + file] = new Date(0)
    }
    fs.stat(strategies_dir + file, function (err, stats) {
      try {
        if (stats.mtime.valueOf() === MessageStrategy.watched_events[strategies_dir + file].valueOf()) {
          return
        }
fork icon0
star icon3
watch icon1

1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
    })
    .reverse();
}
function getCharaterFile2(directories,i){
    if(directories.length > i){
            fs.stat('public/characters/'+directories[i]+'/'+directories[i]+".json", function(err, stat) {
                if (err == null) {
                    fs.readFile('public/characters/'+directories[i]+'/'+directories[i]+".json", 'utf8', (err, data) => {
                        if (err) {
                          console.error(err);
fork icon0
star icon1
watch icon1

+ 7 other calls in file

719
720
721
722
723
724
725
726
727
728
if (entryName === "." || entryName === "..") {
    continue;
}

const entryPath = `${dirPath}/${entryName}`;
const entryStat = await fs.stat(entryPath);
if (entryStat.isDirectory()) {
    await removeDir(entryPath);
    await fs.rmdir(entryPath);
}
fork icon0
star icon1
watch icon1

3
4
5
6
7
8
9
10
11
12

dbDir = "/etc/TerminusBot/TBotZap/usuarios/database_users.json"

createUserDatabase({newUser}){
    
    fs.stat(this.dbDir, (error, stats) => {
       if(error){
        fs.writeFile(this.dbDir, JSON.stringify([newUser], null, 4), (error, bytes) => {
            if(error){
                console.log(`Erro ao salvar pedido: ${error}`)
fork icon1
star icon0
watch icon1

389
390
391
392
393
394
395
396
397
398
399


function stat(file, callback, force) {
  if (force) {
    return callback(true);
  }
  fs.stat(file, function (err) {
    if (!err || err.code === 'ENOTDIR') {
      return callback();
    }
    if (err.code === 'ENOENT') {
fork icon0
star icon0
watch icon1

+ 3 other calls in file

34
35
36
37
38
39
40
41
42
43
44
45
    }
  };


  !file || typeof file != 'string'
    ? execCallback()
    : fs.stat(file, execCallback);
}


function parseRes(str, rawHeaderNames, fromValue) {
  if (!str) {
fork icon0
star icon0
watch icon1

221
222
223
224
225
226
227
228
229
230
const fs = require('fs');

const pathsToCheck = ['./txtDir', './txtDir/file.txt'];

for (let i = 0; i < pathsToCheck.length; i++) {
  fs.stat(pathsToCheck[i], function(err, stats) {
    console.log(stats.isDirectory());
    console.log(stats);
  });
}
fork icon0
star icon0
watch icon1

834
835
836
837
838
839
840
841
842
var objToReturn = {};
// then using async do like this
var data = [];
async.eachSeries(files, function (file, callback) {
    var filePath = path.join(dirPath, file);
    const dnt = fs.stat(filePath, function (err, stats) {
        // write stats data into objToReturn 

        callback(null, data.push({
fork icon0
star icon0
watch icon1