How to use fs-extra

Comprehensive fs-extra code examples:

How to use fs-extra.appendFileAsync:

115
116
117
118
119
120
121
122
123
124

  // Should look something like: "ver:<<{{10024121ae3fa7fc60a5945be1e155520fb929dd}}>>;"
  var hashDef = "#define VERSION_HASH F(\"ver:<<{{" + hash + "}}>>;\")\n";

  // Append a define to the compile options
  return fs.appendFileAsync( path.join(stagedSketchDir, 'CompileOptions.h'), hashDef );
})

// TODO:
// Generate hash for the board core

How to use fs-extra._toUnixTimestamp:

139
140
141
142
143
144
145
146
147
148
return async (currentTree, { relpath, status }) => {
  const inode = status.ino
  const onfile = mod.treeOps.getOnFileData(trees.target, inode, relpath)
  const data = {
    size: status.size,
    mtime: fs._toUnixTimestamp(status.mtime),
    isutf8: onfile.isutf8
  }

  let hashsum = mod.treeOps.getHashByInode(trees.target, inode)

How to use fs-extra.walk:

181
182
183
184
185
186
187
188
189
190
  col.lastUpdated = moment().format()
  col.seeds = []
}
col.created = moment().format()
let size = 0
fs.walk(col.archive)
  .pipe(through2.obj(function (item, enc, next) {
    if (!item.stats.isDirectory()) this.push(item)
    next()
  }))

How to use fs-extra.opendir:

2
3
4
5
6
7
8
9
10
11
12


const walk = async (root, visit) => new Promise((resolve, reject) => {
  let outstanding = 1;
  
  async function process(dir) {
    const listing = await fse.opendir(dir);
    
    const subdirs = [], others = [];
    for await (const entry of listing) {
      if (entry.isDirectory()) {

How to use fs-extra.fstat:

79
80
81
82
83
84
85
86
87
88
fs.watchFile(child, { interval: 300 }, (curr, prev) => {
  if (curr.mtime > prev.mtime) {
    fs.open(parent, 0, function(err, fd) {
      if (err) return console.log(err)

      fs.fstat(fd, function(err) {
        if (err) return console.log(err)
        var now = Date.now()

        var a = parseInt(now / 1000, 10)

How to use fs-extra.outputFileAsync:

229
230
231
232
233
234
235
236
237
238
            logger.error(" - Unable to find android key for", keyForReplace);
          }
        }
      }

      return fs.outputFileAsync(outFile, contents, 'utf-8');
    });
} else if (ext == '.so') {
  var src = path.join(baseDir, filePath);
  var basename = path.basename(filePath);

How to use fs-extra.Stats:

25
26
27
28
29
30
31
32
33
34
function _mtimeFromEntry(entry) {
  return yauzl.dosDateTimeToDate(entry.lastModFileDate, entry.lastModFileTime);
}

function _processZipEntry(zip, dest, entry) {
  const stat = new fs.Stats();
  stat.mode = _modeFromEntry(entry);
  stat.mtime = _mtimeFromEntry(entry);

  if (stat.isDirectory()) {

How to use fs-extra.truncateSync:

522
523
524
525
526
527
528
529
530
531
});

it('throws when opening an empty file', function(){
    index = createIndex('.index');
    index.close();
    fs.truncateSync(index.fileName, 0);
    expect(() => createReader(index.name)).to.throwError(/empty/);
});

it('allows multiple readers for a single index', function(){

How to use fs-extra.lchownSync:

124
125
126
127
128
129
130
131
132
133
    logwarn('Symlink target doesn\'t exist: ' + realpath);
  }
}
if (data.hasOwnProperty('uid') && data.hasOwnProperty('gid')) {
  logdebug('Setting UID ' + data.uid + ', GID ' + data.gid + ' for ' + path);
  fs.lchownSync(path, data.uid, data.gid);
  if (followSymlink) {
    fs.chownSync(realpath, data.uid, data.gid);
  }
}

How to use fs-extra.ensureSymlinkAsync:

105
106
107
108
109
110
111
112
113
114
}).then(() => {
  const symlinkType = paths.getSymlinkType()

  debug('making symlink from %s to %s of type %s', appPath, dest, symlinkType)

  return fs.ensureSymlinkAsync(appPath, dest, symlinkType)
}).then(() => {
  const execPath = paths.getPathToExec()

  if (isSandboxNeeded()) {

How to use fs-extra.ftruncateAsync:

62
63
64
65
66
67
68
69
70
71
72
  ]);
}


function createLoopMount(file, dir, size) {
  return Promise.using(sbutil.withOpen(file, 'wx'), function (fd) {
      return fs.ftruncateAsync(fd, size);
  }).then(function () {
    return sbutil.execFilePromise('mkfs.btrfs', [file])
      .then(function () {
        return exports.mountLoopFile(file, dir);

How to use fs-extra.emptyDirAsync:

88
89
90
91
92
93
94
95
  /**
   * Delete Fusebox cache
   */
  () => {
    console.info(colors.white('  └── ') + colors.green('Clearing fuse-box cache...'))
    return fs.emptyDirAsync('./.fusebox')
  }
], f => { return f() })

How to use fs-extra.createFile:

147
148
149
150
151
152
153
154
155
156
    'url': 'http://' + config.fdfs.download.host + '/' + fileId,
    'title': req.body && req.body.pictitle || filename,
    'original': filename,
    'state': 'SUCCESS'
  };
fse.createFile(path.join(static_url, img_url, 'fdfs.list'), function(err) {
  if (err) throw err;
  fs.open(path.join(static_url, img_url, 'fdfs.list'), 'a', function(err, fd) {
    if (err) throw err;
    fs.write(fd, '\n'+JSON.stringify(result), function(e) {

How to use fs-extra.mkdirAsync:

228
229
230
231
232
233
234
235
236
237
  data = data.replace(/,\s*shang-auto-generate/gi, '');
  data = data.replace(`<component name="JavaScriptLibraryMappings">`, `<component name="JavaScriptLibraryMappings">\n    <file url="file://$PROJECT_DIR$/${typingScope}" libraries="{shang-auto-generate}" />\n`);
  return fs.writeFileAsync(jsLibraryMappingsXmlPath, data);
})
.then(function () {
  return fs.mkdirAsync(librariesPath)
    .catch(function () {
    });
})
.then(function () {

How to use fs-extra.unlinkAsync:

105
106
107
108
109
110
111
112
113
114
  glob.sync(`${store.get('itemset_path')}**/CGG_*.json`),
  glob.sync(`${store.get('itemset_path')}**/CIFY_*.json`)
];

return Promise.resolve(R.flatten(globbed))
  .each(f => fs.unlinkAsync(f))
  .catch(err => Log.warn(err))
  .then(() => {
    if (deletebtn !== true) progressbar.incr(2.5);
  });

How to use fs-extra.watch:

598
599
600
601
602
603
604
605
606
const tmpDir = path.join(os.tmpdir(), 'apps-tmp', manifest.id);
if (homey.platform === 'local') {
  await fse.ensureDir(tmpDir);
  await fse.emptyDir(tmpDir);

  fse.watch(tmpDir, (_, filename) => {
    Log(colors.gray(`Modified: ${path.join(tmpDir, filename)}`));
  });
}

How to use fs-extra.outputJsonAsync:

76
77
78
79
80
81
82
83
84
85
      console.info(colors.white('      ' + lang + '.json'))
      let outputPath = path.join('./assets/js/i18n', lang + '.json')
      return fs.readJsonAsync(path.join('./server/locales', lang, 'browser.json'), 'utf8').then((content) => {
        return fs.outputJsonAsync(outputPath, _.defaultsDeep(content, enContent))
      }).catch(err => { // eslint-disable-line handle-callback-err
        return fs.outputJsonAsync(outputPath, enContent)
      })
    })
  })
})

How to use fs-extra.WriteStream:

9154
9155
9156
9157
9158
9159
9160
9161
9162
9163

var fs$ReadStream = fs.ReadStream
ReadStream.prototype = Object.create(fs$ReadStream.prototype)
ReadStream.prototype.open = ReadStream$open

var fs$WriteStream = fs.WriteStream
WriteStream.prototype = Object.create(fs$WriteStream.prototype)
WriteStream.prototype.open = WriteStream$open

fs.ReadStream = ReadStream

How to use fs-extra.outputJSONSync:

17
18
19
20
21
22
23
24
25
26
27
    path = require("path");


let writeJSONToDiskSync = (path, JSONData) => {
    let fd;
    try {
        fs.outputJSONSync(path, JSONData);
        fd = fs.openSync(path, 'rs+');
        fs.fdatasyncSync(fd);
        return true;
    } catch (e) {

How to use fs-extra.fchmod:

9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
  if (callback) callback(err)
  return
}
// prefer to return the chmod error, if one occurs,
// but still try to close, and report closing errors if they occur.
fs.fchmod(fd, mode, function (err) {
  fs.close(fd, function(err2) {
    if (callback) callback(err || err2)
  })
})

How to use fs-extra.readJsonAsync:

68
69
70
71
72
73
74
75
76
77
 * i18n
 */
() => {
  console.info(colors.white('  └── ') + colors.green('Copying i18n client files...'))
  return fs.ensureDirAsync('./assets/js/i18n').then(() => {
    return fs.readJsonAsync('./server/locales/en/browser.json').then(enContent => {
      return fs.readdirAsync('./server/locales').then(langs => {
        return Promise.map(langs, lang => {
          console.info(colors.white('      ' + lang + '.json'))
          let outputPath = path.join('./assets/js/i18n', lang + '.json')

How to use fs-extra.ftruncateSync:

404
405
406
407
408
409
410
411
412
partition.open();
const position = fillPartition(5);
partition.close();

let fd = fs.openSync('test/data/.part', 'r+');
fs.ftruncateSync(fd, partition.headerSize + position + Partition.DOCUMENT_HEADER_SIZE + 4);
fs.closeSync(fd);

partition.open();

How to use fs-extra.chownSync:

144
145
146
147
148
149
150
151
152
            stream.write({rx: data.length / meta.size});
        });

        stream.on('end', function () {
            Logger.verbose(Util.format('Updating file perms for %s (changing to %s:%s)', file.path, server.config.user, server.config.user));
            Fs.chownSync(file.path, Userid.uid(server.config.user), Userid.gid(server.config.user));
        });
    });
});

How to use fs-extra.truncate:

241
242
243
244
245
246
247
248
249
250
- fs.realpath():将相对文件路径指针(.,..)解析为完整路径
- fs.rename():重命名文件或文件夹
- fs.rmdir():删除文件夹
- fs.stat():返回由传递的文件名标识的文件的状态。相关阅读:fs.fstat(),fs.lstat()
- fs.symlink():创建指向文件的新符号链接
- fs.truncate():将传递的文件名标识的文件截断为指定的长度。有关:fs.ftruncate()
- fs.unlink():删除文件或符号链接
- fs.unwatchFile():停止监视文件上的更改
- fs.utimes():更改通过传递的文件名标识的文件的时间戳。有关:fs.futimes()
- fs.watchFile():开始监视文件上的更改。有关:fs.watch()

How to use fs-extra.fdatasync:

446
447
448
449
450
451
452
453
454
455
    });

    partition.write('foo');
    expect(partition.size).to.be.greaterThan(reader.size);
    partition.flush();
    fs.fdatasync(partition.fd);
});

it('updates reader when writer truncates', function(done){
    partition.open();

How to use fs-extra.emptydirSync:

616
617
618
619
620
621
622
623
624
async generate(baseUrl) {
  const startTime = new Date();
  // Create the .tmp folder for storing intermediate results.
  fs.emptydirSync(this.tempPath);
  // Clean the output folder; create it if not exist.
  fs.emptydirSync(this.outputPath);
  const lazyWebsiteGenerationString = this.onePagePath ? '(lazy) ' : '';
  logger.info(`Website generation ${lazyWebsiteGenerationString}started at ${
    startTime.toLocaleTimeString()}`);

How to use fs-extra.fchmodSync:

164
165
166
167
168
169
170
171
172
173

try {
    fs.writeFileSync(envelopePath, buffer);  // lgtm [js/path-injection]
    console.log(`ℹ️ [info] [notifier.js] Deploying build envelope: ${deployedEnvelopePath}`);
    fs.writeFileSync(deployedEnvelopePath, buffer);  // lgtm [js/path-injection]
    fs.fchmodSync(fs.openSync(deployedEnvelopePath), 0o665);  // lgtm [js/path-injection]
} catch (e) {
    console.log("☣️ [error] Envelope write failed to", deployedEnvelopePath);
    return callback(false);
}

How to use fs-extra.fdatasyncSync:

55
56
57
58
59
60
61
62
63
64
        expect(filename).to.be('.file');
        fs.closeSync(fd);
        done();
    });
    fs.writeSync(fd, 'foobar');
    fs.fdatasyncSync(fd);
});

it('detects file creations inside a directory', function(done){
    let fd;

How to use fs-extra.split:

49
50
51
52
53
54
55
56
57
58
const fsLines = fsString.split('\n').filter((part) => part != '');
const header = fsLines[0].split(' ').filter((part) => part != '');
const fileSystems = fsLines.slice(1);
const parsedOutput = {};
for (const fs of fileSystems) {
    const lineParts = fs.split(' ').filter((part) => part != '');
    parsedOutput[lineParts[0]] = {};
    for (let i=1; i < header.length; i++) {
        if (lineParts[i]) {
            parsedOutput[lineParts[0]][header[i].toLowerCase()] = lineParts[i];

How to use fs-extra.chown:

113
114
115
116
117
118
119
120
121
122
    await copyFileContent(source, output, options.transform)
}
await fs.chmod(output, stat.mode)

if (options.preserve) {
    await fs.chown(output, stat.uid, stat.gid)
    await fs.utimes(output, stat.atime, stat.mtime)
}

return { source, output, skipped: false }