How to use fs-promise

Comprehensive fs-promise code examples:

How to use fs-promise.access:

719
720
721
722
723
724
725
726
727
728
const isExecutable = co.wrap(function *(repo, filename) {
    assert.instanceOf(repo, NodeGit.Repository);
    assert.isString(filename);
    const fullPath = path.join(repo.workdir(), filename);
    try {
        yield fs.access(fullPath, fs.constants.X_OK);
        return true;
    } catch (e) {
        // cannot execute
        return false;

How to use fs-promise.ensureDir:

57
58
59
60
61
62
63
64
65
66
67
// Write the '.oathframe.json' file for this directory.
Directory.writeJSON = function(data, options) {
  options = options || {};
  options = Object.assign({encoding:'utf8'}, options);


  return fs.ensureDir(this.filepath())
    .then(() => fs.writeFile(this.physicalFilepath(), JSON.stringify(data), options))
    .then(() => {
      console.error('Wrote: ' + this.filepath() + path.sep);  // eslint-disable-line no-console
      return this;

How to use fs-promise.statSync:

132
133
134
135
136
137
138
139
140
141
142
143
var Mount = module.exports = function(options) {
  this.options = options
  this.fds = []
  for (var i = 0; i < 10; i++) this.fds.push(null)


  this.top = new CachedDir(options.sourceDir, fs.statSync(options.sourceDir), this)
  this.deleter = child_process.fork(__dirname + "/deleter")
}


Mount.prototype.mount = function() {

How to use fs-promise.emptyDirSync:

8
9
10
11
12
13
14
15
16
17
18
19


const {S3_BUCKET, IO_LOCAL_PATH} = process.env;


if (IO_LOCAL_PATH) {
    
    fs.emptyDirSync(IO_LOCAL_PATH);
    
    const http = require('http');
    const static = require('node-static');

How to use fs-promise.mkdirs:

29
30
31
32
33
34
35
36
37
38
39
    process.exit(1);
}


const uploadLocal = function(pathToUpload, content) {
    let dirname = path.dirname(pathToUpload);
    return fs.mkdirs(path.join(IO_LOCAL_PATH, dirname))
    .then(() => {
        return fs.writeFile(path.join(IO_LOCAL_PATH, pathToUpload), content)
    })
}

How to use fs-promise.watch:

44
45
46
47
48
49
50
51
52
53
    for (var i = 0; i < files.length; i++) {
      var file = files[i]
      if (!(file in self.cache)) self.cache[file] = dummy
    }
    if (self.watching) self.watching.close()
    self.watching = fs.watch(self.path, self.listen.bind(self))
    return self.cache
  })
}

How to use fs-promise.createReadStream:

166
167
168
169
170
171
172
173
174
175
    const errorMessage = `File ${fileUuid} not found`;
    throw errorMessage;
  }
  const fileName = file.name;
  ctx.res.setHeader('Content-disposition', `attachment; filename=${fileName}`);
  ctx.body = fs.createReadStream(file.filePath);
} catch (ex) {
  ctx.status = 500;
  ctx.body = new Response(ctx, requestDescription, ex);
  logger.error(ex);

How to use fs-promise.createFile:

15
16
17
18
19
20
21
22
23
24
  return
}

const newFile = path.join(os.tmpdir(), 'foobar.txt')

return fs.createFile(newFile)
  .then(() => {
    return workspace.openTextDocument(newFile)
  })
  .then(doc => {

How to use fs-promise.ensureFile:

108
109
110
111
112
113
114
115
116
117
.then(sortResp)
// Write last read file of each type to a metadata file in the dest
.then((resp) => {
  resp[constants.METADATA] = lastReadFiles(resp)
  const p = options.real && device
    ? fs.ensureFile(device).then(() => fs.writeJson(device, resp[constants.METADATA], {spaces: 0}))
    : Promise.resolve()
  return p.then(() => resp)
})
// Always close the exiftool stream

How to use fs-promise.outputJsonSync:

58
59
60
61
62
63
64
65
66
67
    name: reqDataName,
    id: reqDataId,
    isComplete: false
});

fsp.outputJsonSync(jsonPath, json, {
    spaces: 4
});

resData = {

How to use fs-promise.remove:

130
131
132
133
134
135
136
137
138
139
describe('grammars-v4/', () => {
  let prev_timeout;
  beforeAll(() => {
    prev_timeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
    jasmine.DEFAULT_TIMEOUT_INTERVAL = 60000;
    return fs.remove(config.build_path).catch(err => {
      console.error(err);
    });
  });
  afterAll(() => {

How to use fs-promise.readdir:

32
33
34
35
36
37
38
39
40
41
42
  return this.read()
}


CachedDir.prototype.read = function() {
  var self = this
  return this.updating = fs.readdir(this.path).then(function(files) {
    self.updating = null
    self.upToDate = true
    for (var file in self.cache) if (files.indexOf(file) == -1) {
      self.cache[file].detach()

How to use fs-promise.readJsonSync:

50
51
52
53
54
55
56
57
58
59
        status: false,
        errorMessage: '参数不合法:请传入对应任务名:name以及任务标识:id',
        data: {}
    };
} else {
    const json = fsp.readJsonSync(jsonPath);

    json.push({
        name: reqDataName,
        id: reqDataId,

How to use fs-promise.lstat:

80
81
82
83
84
85
86
87
88
89
90
91


// String ~> Promise Bool
const isDirectory = path =>
  fsp.exists(path)
    .then(assert)
    .then(() => fsp.lstat(path))
    .then(stats => stats.isDirectory())
    .catch(() => false);


// String -> Promise String

How to use fs-promise.writeFile:

981
982
983
984
985
986
987
988
989
990
rast = yield ReadRepoASTUtil.readRAST(repo, false);
assert.deepEqual(remainingCommits, rast.sequencerState.commits);
assert.equal(2, rast.sequencerState.currentCommit);

//finally, we'll do it again, which should finish this up
yield fs.writeFile(path.join(repo.workdir(), "s", "a"), "resolv2");
try {
    yield CherryPickUtil.continue(repo);
    assert.equal(1, 2); //fail
} catch (e) {

How to use fs-promise.mkdir:

53
54
55
56
57
58
59
60
61
62
 *
 */
async createUploadDirectory() {
  const directoryExists = await fs.exists(this.uploadDir);
  if (!directoryExists) {
    await fs.mkdir(this.uploadDir);
  }
}

/**

How to use fs-promise.stat:

76
77
78
79
80
81
82
83
84
85
if (fileExtension === undefined) {
  return;
}
const name = `${filename.split(`_${uuid}`)[0]}.${filename.split('.')[1]}`;
const filePath = `${basedir}/${filename}`;
const fileStats = await fs.stat(filePath);
const dateChanged = fileStats.ctime;

const fileObject = {
  uuid,

How to use fs-promise.copy:

40
41
42
43
44
45
46
47
48
49
  }
},
async start(server) {
  if (!server.process) {
    if (server.dbKey !== server.dbFile) {
      await fs.copy(`${server.dbKey}.mv.db`, `${server.dbFile}.mv.db`);
    }

    server.process = spawn(
      "java",

How to use fs-promise.unlink:

239
240
241
242
243
244
245
246
247
248
249
        }
    } finally {
        if (release !== null) {
            release();
        }
        yield fs.unlink(tempIndexPath);
    }
});



How to use fs-promise.mkdirsSync:

81
82
83
84
85
86
87
88
89
90
91
92
window.utoa = utoa
window.atou = atou


const userPath = path.join(app.getPath('home'), '/.rcs-16')
if (!fs.existsSync(userPath)) {
  fs.mkdirsSync(userPath)
}


const name = app.getName()
const version = app.getVersion()

How to use fs-promise.readJson:

398
399
400
401
402
403
404
405
406
407
408
409


async function writeAt(filePath, jsonPath, value) {
  mkdirp.sync(getDirName(filePath));


  try {
    const json = await fs.readJson(filePath);
    set(json, jsonPath, value);
    return await fs.writeJson(filePath, json);
  } catch (error) {
    // eslint-disable-next-line   

How to use fs-promise.write:

6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
  /*.replace(/<[^>]*>/g, function(x) {
    return x.replace(/\s+ng-\S+="[^"]*"/g, '');
  })*/

var tmp_html = tmp.fileSync({postfix: '.html'});
await fsp.write(tmp_html.fd, html);

var tmp_pdf = tmp.fileSync({postfix: '.pdf'});
let args = ['--base-url', baseurl, tmp_html.name, tmp_pdf.name];
console.log('weasyprint' + ' ' + args.join(' '));

How to use fs-promise.readFile:

117
118
119
120
121
122
123
124
125
126
127
  return this.read()
}


CachedFile.prototype.read = function() {
  var self = this
  return this.updating = fs.readFile(this.path).then(function(content) {
    self.updating = null
    var filter = self.mount.options.filter
    self.data = filter ? filter(self.path, content) : content
    self.mtime = new Date

How to use fs-promise.exists:

51
52
53
54
55
56
57
58
59
60
 * Create an upload directory where specified by Escher.uploadDir
 * unless it already exists
 *
 */
async createUploadDirectory() {
  const directoryExists = await fs.exists(this.uploadDir);
  if (!directoryExists) {
    await fs.mkdir(this.uploadDir);
  }
}

How to use fs-promise.unlinkSync:

154
155
156
157
158
159
160
161
162
163
this.user.icon = `https://storage.googleapis.com/hs-profile-picture/${fileID}`;
return Users.update({
    _id: this.user._id,
}, this.user).then(() => {
    // Remove the icon from local disk
    fp.unlinkSync(filePath);
    res.json({
        icon: this.user.icon,
    });
});

How to use fs-promise.rename:

138
139
140
141
142
143
144
145
146
147
// Rename the file from it's random name to the file's name plus the uuid
const nameArray = name.split('.');
const fileName = nameArray[0];
const fileExt = nameArray[1];
const filenameWithUuid = `${this.uploadDir}/${fileName}_${uuid}.${fileExt}`;
await fs.rename(file.path, filenameWithUuid);
this.fileList[uuid] = fileObject;
this.app.io.broadcast('fileEvent', {
  uuid,
  event: 'new',

How to use fs-promise.writeJson:

132
133
134
135
136
137
138
139
140
141

return fs
  .readJson(filePath)
  .then(function (json) {
    set(json, jsonPath, value);
    return fs.writeJson(filePath, json);
  })
  .catch(function (error) {
    const json = {};
    set(json, jsonPath, value);