Skip to content

Latest commit

 

History

History
48 lines (37 loc) · 1.59 KB

fs-read-write-writev.md

File metadata and controls

48 lines (37 loc) · 1.59 KB

About fs.read() & fs.write()

fs.read(), fs.write(), & fs.writev() are different from other fs methods in that their callbacks are called with 3 arguments instead of the usual 2 arguments.

If you're using them with callbacks, they will behave as usual. However, their promise usage is a little different. fs-extra promisifies these methods like util.promisify() (only available in Node 8+) does.

Here's the example promise usage:

fs.read()

// With Promises:
fs.read(fd, buffer, offset, length, position)
  .then(results => {
    console.log(results)
    // { bytesRead: 20, buffer: <Buffer 0f 34 5d ...> }
  })

// With async/await:
async function example () {
  const { bytesRead, buffer } = await fs.read(fd, Buffer.alloc(length), offset, length, position)
}

fs.write()

// With Promises:
fs.write(fd, buffer, offset, length, position)
  .then(results => {
    console.log(results)
    // { bytesWritten: 20, buffer: <Buffer 0f 34 5d ...> }
  })

// With async/await:
async function example () {
  const { bytesWritten, buffer } = await fs.write(fd, Buffer.alloc(length), offset, length, position)
}

fs.writev()

// With async/await:
async function example () {
  const { bytesWritten, buffers } = await fs.writev(fd, buffers, position)
}