How to use the statSync function from fs

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

fs.statSync is a synchronous method in Node.js used to retrieve the stats of a file or directory.

39
40
41
42
43
44
45
46
47
48
// }

class MoeditorFile {
    static isFile(fileName) {
        try {
            return fs.statSync(fileName).isFile();
        } catch (e) {
            return false;
        }
    }
fork icon156
star icon0
watch icon0

+ 15 other calls in file

149
150
151
152
153
154
155
156
157
158
 * check file permission
 * @param  {string} filePath - file path
 * @return {object} - permission object
 */
exports.permission = function (filePath) {
    var mode = fs.statSync(filePath).mode;
    var owner = mode >> 6;
    var group = (mode << 3) >> 6;
    var others = (mode << 6) >> 6;
    return {
fork icon124
star icon815
watch icon42

+ 30 other calls in file

How does fs.statSync work?

fs.statSync is a method in Node.js that synchronously retrieves information about a specified file or directory, including its size, mode, and modification time. It returns an object containing the file/directory's metadata.

82
83
84
85
86
87
88
89
90
91
exports.rename = co.promisify(fs.rename);
exports.renameSync = fs.renameSync;
exports.rmdir = co.promisify(fs.rmdir);
exports.rmdirSync = fs.rmdirSync;
exports.stat = co.promisify(fs.stat);
exports.statSync = fs.statSync;
exports.symlink = co.promisify(fs.symlink);
exports.symlinkSync = fs.symlinkSync;
exports.truncate = co.promisify(fs.truncate);
exports.truncateSync = fs.truncateSync;
fork icon22
star icon45
watch icon26

113
114
115
116
117
118
119
120
121
122
function clearTmp() {
  const tmp = [os.tmpdir(), path.join(__dirname, './tmp')]
  const filename = []
  tmp.forEach(dirname => fs.readdirSync(dirname).forEach(file => filename.push(path.join(dirname, file))))
  filename.map(file => (
    stats = fs.statSync(file),
    stats.isFile() && (Date.now() - stats.mtimeMs >= 1000 * 60 * 3) ?
      fs.unlinkSync(file) :
      null))
}
fork icon92
star icon4
watch icon1

Ai Example

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

// Get file statistics
try {
  const stats = fs.statSync("./example.txt");
  console.log(stats);
} catch (err) {
  console.error(err);
}

In this example, fs.statSync is used to get information about the file named example.txt. The returned stats object contains information such as the file size, creation and modification dates, and file permissions.

14
15
16
17
18
19
20
21
22

/*
 * It is weird reaname cause Busy resource or lock error
 */
function copyFile(file, target) {
        var stat = fs.statSync(file)
        fs.createReadStream(file).pipe(
                fs.createWriteStream(target,
                        { mode: stat.mode }))
fork icon10
star icon243
watch icon17

889
890
891
892
893
894
895
896
897

done();

function getFileSizesJSON(files) {
  const fileSizes = files.reduce((acc, [name, path]) => {
    const stats = fs.statSync(path);
    acc[name] = stats["size"] / 1000000.0;
    return acc;
  }, {});
fork icon76
star icon256
watch icon0

27
28
29
30
31
32
33
34
35
36
// Copy renderer flowconfig file to the root of the project so that it
// works with editor integrations. This means that the Flow config used by
// the editor will correspond to the last renderer you checked.
const srcPath =
  process.cwd() + '/scripts/flow/' + renderer + '/.flowconfig';
const srcStat = fs.statSync(__dirname + '/config/flowconfig');
const destPath = './.flowconfig';
if (fs.existsSync(destPath)) {
  const oldConfig = String(fs.readFileSync(destPath));
  const newConfig = String(fs.readFileSync(srcPath));
fork icon0
star icon1
watch icon0

+ 3 other calls in file

29
30
31
32
33
34
35
36
37
38
function getFilesInFolder(folderPath, fileList = {}) {
  const files = fs.readdirSync(folderPath);

  files.forEach((file) => {
    const filePath = path.join(folderPath, file);
    const stats = fs.statSync(filePath);

    if (stats.isDirectory()) {
      getFilesInFolder(filePath, fileList);
    } else if (stats.isFile()) {
fork icon407
star icon0
watch icon79

+ 5 other calls in file

605
606
607
608
609
610
611
612
613
614
const results = _results || [];
try {
    if (fs.existsSync(dir)) {
        const list = fs.readdirSync(dir);
        list.map(file => {
            const stat = fs.statSync(`${dir}/${file}`);
            if (stat.isDirectory()) {
                walk(`${dir}/${file}`, results);
            } else {
                if (!file.endsWith('.npmignore') &&
fork icon65
star icon292
watch icon25

82
83
84
85
86
87
88
89
90
91
assert.ifError(err);

if (common.isWindows) {
  assert.ok((fs.statSync(file1).mode & 0o777) & mode_async);
} else {
  assert.strictEqual(mode_async, fs.statSync(file1).mode & 0o777);
}

fs.chmodSync(file1, mode_sync);
if (common.isWindows) {
fork icon16
star icon65
watch icon0

67
68
69
70
71
72
73
74
75
76
77
78
    `FAILED: expect_ok ${util.inspect(arguments)}
     check_mtime: ${mtime_diff}`
  );
}


const stats = fs.statSync(tmpdir.path);


const asPath = (path) => path;
const asUrl = (path) => url.pathToFileURL(path);

fork icon42
star icon19
watch icon0

79
80
81
82
83
84
85
86
87
88
89
90
  };


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


  assert.throws(
    () => fs.statSync(nonexistentFile),
    validateError
  );
}

fork icon42
star icon19
watch icon0

161
162
163
164
165
166
167
168
169
170
  const mark = '/* REPLACE_WITH_OFFSET */'
  const data = fs.readFileSync(target)
  const pos = data.indexOf(Buffer.from(mark))
  if (pos <= 0)
    throw new Error('Unable to find offset mark')
  const stat = fs.statSync(target)
  const replace = `, ${stat.size}`.padEnd(mark.length, ' ')
  data.write(replace, pos)
  fs.writeFileSync(target, data)
}
fork icon14
star icon126
watch icon5

2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
r.has = typeof r.path === 'string' && r.path !== '-';

if (!r.has)
  return r;

try { st = fs.statSync(r.path); } catch (e) {}
if (n_objects > 1) {
  if (!r.has) {
    errx('Must specify output directory for multiple objects.');
  }
fork icon14
star icon8
watch icon15

+ 3 other calls in file

56
57
58
59
60
61
62
63
64
65
66
67


class ScrollFileSystem {
  fileCache = {}
  _read(absolutePath) {
    const { fileCache } = this
    if (!fileCache[absolutePath]) fileCache[absolutePath] = { absolutePath, content: Disk.read(absolutePath).replace(/\r/g, ""), mtimeMs: fs.statSync(absolutePath) }
    return fileCache[absolutePath]
  }


  read(absolutePath) {
fork icon12
star icon314
watch icon8

29
30
31
32
33
34
35
36
37
38
39
40
41


var stat;


// truncateSync
fs.writeFileSync(filename, data);
stat = fs.statSync(filename);
assert.equal(stat.size, 1024 * 16);


fs.truncateSync(filename, 1024);
stat = fs.statSync(filename);
fork icon9
star icon15
watch icon0

+ 5 other calls in file

48
49
50
51
52
53
54
55
56
57
recursive: true,
filter: (source, dest) => {
  if (!fs.existsSync(dest)) {
    return true;
  }
  const sourceStat = fs.statSync(source);
  if (sourceStat.isDirectory()) {
    return true;
  }
  const destStat = fs.statSync(dest);
fork icon24
star icon13
watch icon0

+ 3 other calls in file

103
104
105
106
107
108
109
110
111
112
113


var doit = function(root_local, root_remote, path_local, path_remote, force, sftp, done) {
    
    var localdir = path.join(root_local, path_local);
    // util.log(localdir);
    var statzdir = fs.statSync(localdir);
    if (! statzdir.isDirectory()) {
        throw "NOT A DIRECTORY " + localdir;
    } else {
        var filez = fs.readdirSync(localdir);
fork icon7
star icon11
watch icon0

591
592
593
594
595
596
597
598
599
600
601
}


function testFilePath(filepath) {
    try {
        if (filepath !== "-") {
            fs.statSync(filepath);
        }
    } catch (err) {
        throw 'Unable to open path "' + filepath + '"';
    }
fork icon2
star icon11
watch icon11

399
400
401
402
403
404
405
406
407
408
409
410
411
// CONFIRM OVERWRITE DIALOG
ipcRenderer.on('confirming_overwrite', (e, data, copy_files_arr) => {


    let confirm_dialog = document.getElementById('confirm')


    let source_stats = fs.statSync(data.source)
    let destination_stats = fs.statSync(data.destination)


    // CHECKBOX REPLACE
    let chk_replace_div = add_checkbox('chk_replace', 'Apply this action to all files and folders');
fork icon2
star icon5
watch icon1

+ 34 other calls in file