How to use the open function from graceful-fs

Find comprehensive JavaScript graceful-fs.open code examples handpicked from public code repositorys.

The graceful-fs.open function allows you to open a file and obtain a file descriptor using graceful-fs, which is a drop-in replacement for the built-in fs module that improves performance and reliability.

23
24
25
26
27
28
29
30
31
32

// 550 millis past UNIX epoch
const d = new Date(1435410243862)
fs.writeFile(tmpfile, 'https://github.com/jprichardson/node-fs-extra/pull/141', err => {
  if (err) return callback(err)
  fs.open(tmpfile, 'r+', (err, fd) => {
    if (err) return callback(err)
    fs.futimes(fd, d, d, err => {
      if (err) return callback(err)
      fs.close(fd, err => {
fork icon1
star icon0
watch icon0

325
326
327
328
329
330
331
332
333
334
// Default the same as node
var mode = options.mode || constants.DEFAULT_FILE_MODE;
var flags = options.flags || 'w';
var position = APPEND_MODE_REGEXP.test(flags) ? null : 0;

fs.open(filepath, flags, mode, onOpen);

function onOpen(openErr, fd) {
  if (openErr) {
    return onComplete(openErr);
fork icon0
star icon0
watch icon1

How does graceful-fs.open work?

The graceful-fs.open method provides a way to open a file using fs.open, but with additional safety features, such as avoiding EMFILE errors on too many open files, and retrying file operations that fail due to certain types of errors.

97
98
99
100
101
102
103
104
105
106
      })
    }
  })
}).then(function thenWriteFile () {
  return new Promise(function (resolve, reject) {
    fs.open(tmpfile, 'w', options.mode, function (err, _fd) {
      fd = _fd
      if (err) reject(err)
      else resolve()
    })
fork icon0
star icon0
watch icon0

+ 3 other calls in file

61
62
63
64
65
66
67
68
69
70
}

// doing this instead of `fs.writeFile` in order to get the ability to
// call `fsync`.
function writeFileAsync (file, data, mode, encoding, cb) {
  fs.open(file, 'w', options.mode, function (err, fd) {
    if (err) return cb(err)
    if (Buffer.isBuffer(data)) {
      return fs.write(fd, data, 0, data.length, 0, syncAndClose)
    } else if (data != null) {
fork icon0
star icon0
watch icon0

+ 2 other calls in file

Ai Example

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

fs.open("file.txt", "w", function (err, fd) {
  if (err) {
    throw err;
  }

  console.log(`File opened with file descriptor ${fd}`);
});

In this example, the open function is called on the fs object with the filename, the file access mode (in this case, 'w' for writing), and a callback function that will be called once the file is opened. If there is an error opening the file, the error is thrown. Otherwise, the file descriptor is logged to the console.