How to use the stat function from fs-extra

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

19
20
21
22
23
24
25
26
27
28
async function getNewestFile(directory, filter = (name) => true) {
	let newestTime = new Date(0);
	let newestFile = null;
	for (let entry of await fs.readdir(directory, { withFileTypes: true })) {
		if (entry.isFile()) {
			let stat = await fs.stat(path.join(directory, entry.name));
			if (filter(entry.name) && stat.mtime > newestTime) {
				newestTime = stat.mtime;
				newestFile = entry.name;
			}
fork icon58
star icon228
watch icon0

827
828
829
830
831
832
833
834
835
836
let foldername = dir.substring(mainDir.length+1);
  if(foldername == ""){foldername="root";}
if (!pending) return done(null, results);
list.forEach(function(file) {
  file = path.resolve(dir, file);
  fs.stat(file, function(err, stat) {
      let filename = file.substring(mainDir.length+1);
    if (stat && stat.isDirectory()) {
      
      walk(file, function(err, res) {
fork icon3
star icon30
watch icon0

291
292
293
294
295
296
297
298
299
300
if (dataset.isRest) return restDatasetsUtils.readStreams(db, dataset)
const filePath = full ? exports.fullFilePath(dataset) : exports.filePath(dataset)

let streams = [fs.createReadStream(filePath)]
if (progress) {
  const { size } = await fs.stat(filePath)
  streams.push(new Transform({
    transform (chunk, encoding, callback) {
      progress((chunk.length / size) * 100)
      callback(null, chunk)
fork icon6
star icon25
watch icon4

+ 15 other calls in file

8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
}


// get the size of a file in bytes given a path to a file
const getFileSizeInBytes = (path) => {
  return new Promise((resolve, reject) => {
    fs.stat(path, (err, stats) => {
      if (err) {
        console.error(err);
        reject(err);
      } else {
fork icon9
star icon22
watch icon9

+ 9 other calls in file

41
42
43
44
45
46
47
48
49
50
- 使用stat方法查看文件的具体信息

```js
const fs = require('fs')
// 获取文件属性
const stats = fs.stat('./http.js',(err,stats)=>{
  console.log(stats);
})
// Stats {
//   dev: 1115740208,
fork icon0
star icon12
watch icon1

+ 27 other calls in file

1129
1130
1131
1132
1133
1134
1135
1136
1137
});

// Make sure archive stream is created after any additional changes to the app
// and right before publishing
const archiveStream = await this._getPackStream();
const { size } = await fse.stat(archiveStream.path);

Log(colors.green(`✓ Created Build ID ${buildId}`));
Log(colors.green(`✓ Uploading ${appId}@${appVersion}...`));
fork icon4
star icon5
watch icon4

256
257
258
259
260
261
262
263
264
265
try {
    const apkPath = path.join(appSaveInfo.appSavePath, `${app.app}.apk`);

    if (fs.existsSync(apkPath)) {
        // Perform a check on apk size
        await fs.stat(apkPath, async(err, stats) => {
            if (stats.size == 0 || stats.size == undefined) {
                await fs.rmdir(appSaveInfo.appSavePath).catch(logger.warning);
                return Promise.reject('File did not successfully download and is a empty size');
            }
fork icon3
star icon3
watch icon2

+ 9 other calls in file

206
207
208
209
210
211
212
213
214
215
try {
    const appPath = path.join(appSaveInfo.appSavePath, `${app.app}.ipa`);

    if (fs.existsSync(appPath)) {
        // Perform a check on ipa size
        await fs.stat(appPath, async(err, stats) => {
            if (stats.size == 0 || stats.size == undefined) {
                await fs.rmdir(appSaveInfo.appSavePath).catch(logger.warning);
                return Promise.reject('File did not successfully download and is a empty size');
            }
fork icon3
star icon3
watch icon2

+ 9 other calls in file

35
36
37
38
39
40
41
42
43
44
// draft, which prevents the draft from spitting
// a new preview file into the folder
contents = contents.sort().reverse();

for (const item of contents) {
  const stat = await fs.stat(join(localFolder, join(dir, item)));
  const directory = stat.isDirectory();
  const file = !directory;
  const formerParentDirectory = renamedDirectories[dir];
  const inMovedDirectory = formerParentDirectory !== undefined;
fork icon69
star icon0
watch icon23

+ 6 other calls in file

166
167
168
169
170
171
172
173
174
175
// Add base64 content of attachments
const attachmentField = dataset.schema.find(f => f['x-refersTo'] === 'http://schema.org/DigitalDocument')
if (attachmentField && flatItem[attachmentField.key]) {
  const filePath = path.join(datasetUtils.attachmentsDir(dataset), flatItem[attachmentField.key])
  if (await fs.pathExists(filePath)) {
    const stats = await fs.stat(filePath)
    if (stats.size > config.defaultLimits.attachmentIndexed) {
      warning = 'Pièce jointe trop volumineuse pour être analysée'
    } else {
      item._attachment_url = `${config.publicUrl}/api/v1/datasets/${dataset.id}/attachments/${flatItem[attachmentField.key]}`
fork icon6
star icon26
watch icon4

+ 13 other calls in file

27
28
29
30
31
32
33
34
35
36
postcssImport,
(css, { messages, opts: { file } }) =>
  Promise.all(
    messages
      .reduce((accum, { file: depPath, type }) => (type === 'dependency' ? accum.concat(depPath) : accum), [])
      .map((importedPath) => fs.stat(importedPath).then(({ mtime }) => mtime))
  ).then((mtimes) => {
    const newestMtime = mtimes.reduce((max, curr) => (!max || curr > max ? curr : max), file.stat.mtime)
    if (newestMtime > file.stat.mtime) file.stat.mtimeMs = +(file.stat.mtime = newestMtime)
  }),
fork icon38
star icon137
watch icon7

+ 4 other calls in file

1341
1342
1343
1344
1345
1346
1347
1348
1349
if (!exists)
    return {filename: 'restricted'};

let stats, err;
try {
    stats = await fs.stat('./PDF/Letter' + PDFname + '.pdf');
} catch (e) {
    err = e;
}
fork icon8
star icon11
watch icon6

+ 11 other calls in file

81
82
83
84
85
86
87
88
89
90
91
module.exports = async function copyFile(source, output, options) {
    const stat = await fs.stat(source)


    if (options.update) {
        try {
            const dstStat = await fs.stat(output)
            if (dstStat.mtime.getTime() > stat.mtime.getTime()) {
                // Don't overwrite because the file on destination is newer than
                // the source file.
                return { source, output, skipped: true }
fork icon3
star icon27
watch icon2

+ 17 other calls in file

824
825
826
827
828
829
830
831
832
833
if(!be.config.nologin){
    return Promise.all([
        fs.stat('unlogged/login.jade').then(function(){
            throw new Error('login.jade must be in client dir not in unlogged');
        },function(){ /*OK, login.jade must not be here */ }),
        fs.stat('client/login.jade').then(function(){
            return Path.resolve(be.rootPath,'client/login');
        },function(){ 
            return Path.join(__dirname,'../for-client/login');
        }).then(function(loginFile){
fork icon3
star icon4
watch icon10

+ 71 other calls in file

34
35
36
37
38
39
40
41
42
43
                      fse.outputFile(getAbsPath(fname),"export var " +varName + " = " +JSON.stringify(obj))
outputFileAsync = (fname, data) => fse.outputFile(getAbsPath(fname),data)
readFileAsync = (fname, encoding) => fse.readFile(getAbsPath(fname),encoding)
readJsonAsync = fname => fse.readJSON(getAbsPath(fname))
readdirAsync = dirname => fse.readdir(getAbsPath(dirname))
statAsync = path => fse.stat(getAbsPath(path))
readJson = fname => fse.readJSON(getAbsPath(fname))
pathExistsAsync = fname => fse.pathExists(getAbsPath(fname))
copyAsync = (src, dest) => fse.copy(src,dest)
ensureDirAsync = dirPath => fse.ensureDir(dirPath)
fork icon1
star icon3
watch icon3

71
72
73
74
75
76
77
78
79
80
81
  return id++
}


exports.exists = function (p) {
  return new Promise(function (resolve, reject) {
    fs.stat(p, function (err, stats) {
      if (err) return resolve(false)
      if (stats.isFile() || stats.isDirectory()) {
        return resolve(true)
      }
fork icon0
star icon2
watch icon0

7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
    if (err) return callback(err)
    callback()
  })
}

fs.stat(file, (err, stats) => { // eslint-disable-line handle-callback-err
  if (!err && stats.isFile()) return callback()
  const dir = path.dirname(file)
  pathExists(dir, (err, dirExists) => {
    if (err) return callback(err)
fork icon0
star icon1
watch icon0

+ 44 other calls in file

455
456
457
458
459
460
461
462
463
464

deleteOldFiles (dir, expireTime = 86400, prefix = 'segment-') {
  fs.readdir(dir, (err, files) => {
    if (err) console.log(err)
    files.forEach((file, index) => {
      fs.stat(path.join(dir, file), (err, stat) => {
        var endTime, now
        if (err) {
          return console.error(err)
        }
fork icon0
star icon0
watch icon1

+ 19 other calls in file

905
906
907
908
909
910
911
912
913
914
}

var project = metadata.name;
return new Promise(function(resolve,reject) {
    var projectPath = fspath.join(projectsDir,project);
    fs.stat(projectPath, function(err,stat) {
        if (!err) {
            var e = new Error("NLS: Project already exists");
            e.code = "project_exists";
            return reject(e);
fork icon0
star icon0
watch icon1

179
180
181
182
183
184
185
186
187
this.prebuiltAsarWarning('prune', !this.opts.prune)
this.prebuiltAsarWarning('derefSymlinks', this.opts.derefSymlinks !== undefined)

const src = path.resolve(this.opts.prebuiltAsar)

const stat = await fs.stat(src)
if (!stat.isFile()) {
  throw new Error(`${src} specified in prebuiltAsar must be an asar file.`)
}
fork icon0
star icon0
watch icon0

+ 8 other calls in file

function icon

fs-extra.readFileSync is the most popular function in fs-extra (9724 examples)