How to use the write function from graceful-fs

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

graceful-fs.write is a method used to write data to a file in a filesystem.

77
78
79
80
81
82
83
84
85
86
    })
  })
}

// Function signature can be
// fs.write(fd, buffer[, offset[, length[, position]]], callback)
// OR
// fs.write(fd, string[, position[, encoding]], callback)
// We need to handle both cases, so we use ...args
exports.write = function (fd, buffer, ...args) {
fork icon808
star icon0
watch icon93

+ 55 other calls in file

88
89
90
91
92
93
94
95
96
97
}

// Check for old, depricated fs.write(fd, string[, position[, encoding]], callback)
if (typeof buffer === 'string') {
  return new Promise((resolve, reject) => {
    fs.write(fd, buffer, a, b, (err, bytesWritten, buffer) => {
      if (err) return reject(err)
      resolve({ bytesWritten, buffer })
    })
  })
fork icon1
star icon0
watch icon0

+ 5 other calls in file

How does graceful-fs.write work?

graceful-fs.write is a method that writes data to a file, creating the file if it doesn't exist, and overwriting the file if it already exists. It returns a write stream that allows the data to be written to the file in chunks, rather than all at once. The method handles errors that may occur during the write process and uses file system calls that are graceful and avoid known issues with the fs module in Node.js.

332
333
334
335
336
337
338
339
340
341
function onOpen(openErr, fd) {
  if (openErr) {
    return onComplete(openErr);
  }

  fs.write(fd, data, 0, data.length, position, onComplete);

  function onComplete(writeErr) {
    callback(writeErr, fd);
  }
fork icon0
star icon0
watch icon1

111
112
113
114
115
116
117
118
119
120
  fs.write(fd, data, 0, data.length, 0, function (err) {
    if (err) reject(err)
    else resolve()
  })
} else if (data != null) {
  fs.write(fd, String(data), 0, String(options.encoding || 'utf8'), function (err) {
    if (err) reject(err)
    else resolve()
  })
} else resolve()
fork icon0
star icon0
watch icon0

+ 7 other calls in file

Ai Example

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

const data = "This is some data to write to the file";
const fd = fs.openSync("test.txt", "w");
const bytesWritten = fs.writeSync(fd, data);
console.log(`${bytesWritten} bytes written to file`);
fs.closeSync(fd);

Example using graceful-fs.writeFile: javascript Copy code

64
65
66
67
68
69
70
71
72
73
// 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) {
      return fs.write(fd, String(data), 0, String(encoding), syncAndClose)
    } else {
      return syncAndClose()
fork icon0
star icon0
watch icon0

+ 5 other calls in file