Skip to content

Commit

Permalink
doc: add fsPromises.readFile() example
Browse files Browse the repository at this point in the history
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 ce3cb29
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions doc/api/fs.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`:
Expand Down

0 comments on commit ce3cb29

Please sign in to comment.