Skip to content
Permalink
Browse files
doc: add fsPromises.readFile() example
Signed-off-by: Tierney Cyren <hello@bnb.im>
PR-URL: #40237
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
  • Loading branch information
bnb authored and danielleadams committed Oct 11, 2022
1 parent 97df9b8 commit ce3cb29319fb37ee74484b5c09ee938942568d89
Showing 1 changed file with 29 additions and 0 deletions.
@@ -1307,6 +1307,35 @@ platform-specific. On macOS, Linux, and Windows, the promise will be rejected
with an error. On FreeBSD, a representation of the directory's contents will be
returned.

An example of reading a `package.json` file located in the same directory of the
running code:

```mjs
import { readFile } from 'node:fs/promises';
try {
const filePath = new URL('./package.json', import.meta.url);
const contents = await readFile(filePath, { encoding: 'utf8' });
console.log(contents);
} catch (err) {
console.error(err.message);
}
```

```cjs
const { readFile } = require('node:fs/promises');
const { resolve } = require('node:path');
async function logFile() {
try {
const filePath = resolve('./package.json');
const contents = await readFile(filePath, { encoding: 'utf8' });
console.log(contents);
} catch (err) {
console.error(err.message);
}
}
logFile();
```

It is possible to abort an ongoing `readFile` using an {AbortSignal}. If a
request is aborted the promise returned is rejected with an `AbortError`:

0 comments on commit ce3cb29

Please sign in to comment.