doc: add fsPromises.readFile() example
Signed-off-by: Tierney Cyren <hello@bnb.im> PR-URL: https://github.com/nodejs/node/pull/40237 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
This commit is contained in:
parent
1124558b65
commit
624dadb007
@ -1313,6 +1313,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`:
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user