UNPKG

1.38 kBMarkdownView Raw
1# About `fs.read()` & `fs.write()`
2
3[`fs.read()`](https://nodejs.org/api/fs.html#fs_fs_read_fd_buffer_offset_length_position_callback) & [`fs.write()`](https://nodejs.org/api/fs.html#fs_fs_write_fd_buffer_offset_length_position_callback) are different from other `fs` methods in that their callbacks are called with 3 arguments instead of the usual 2 arguments.
4
5If 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()`](https://nodejs.org/api/util.html#util_util_promisify_original) (only available in Node 8+) does.
6
7Here's the example promise usage:
8
9## `fs.read()`
10
11```js
12// With Promises:
13fs.read(fd, buffer, offset, length, position)
14 .then(results => {
15 console.log(results)
16 // { bytesRead: 20, buffer: <Buffer 0f 34 5d ...> }
17 })
18
19// With async/await:
20async function example () {
21 const { bytesRead, buffer } = await fs.read(fd, Buffer.alloc(length), offset, length, position)
22}
23```
24
25## `fs.write()`
26
27```js
28// With Promises:
29fs.write(fd, buffer, offset, length, position)
30 .then(results => {
31 console.log(results)
32 // { bytesWritten: 20, buffer: <Buffer 0f 34 5d ...> }
33 })
34
35// With async/await:
36async function example () {
37 const { bytesWritten, buffer } = await fs.write(fd, Buffer.alloc(length), offset, length, position)
38}
39```