Skip to content

Commit 624dadb

Browse files
authored
doc: add fsPromises.readFile() example
Signed-off-by: Tierney Cyren <[email protected]> PR-URL: #40237 Reviewed-By: James M Snell <[email protected]> Reviewed-By: Antoine du Hamel <[email protected]>
1 parent 1124558 commit 624dadb

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

doc/api/fs.md

+29
Original file line numberDiff line numberDiff line change
@@ -1313,6 +1313,35 @@ platform-specific. On macOS, Linux, and Windows, the promise will be rejected
13131313
with an error. On FreeBSD, a representation of the directory's contents will be
13141314
returned.
13151315
1316+
An example of reading a `package.json` file located in the same directory of the
1317+
running code:
1318+
1319+
```mjs
1320+
import { readFile } from 'node:fs/promises';
1321+
try {
1322+
const filePath = new URL('./package.json', import.meta.url);
1323+
const contents = await readFile(filePath, { encoding: 'utf8' });
1324+
console.log(contents);
1325+
} catch (err) {
1326+
console.error(err.message);
1327+
}
1328+
```
1329+
1330+
```cjs
1331+
const { readFile } = require('node:fs/promises');
1332+
const { resolve } = require('node:path');
1333+
async function logFile() {
1334+
try {
1335+
const filePath = resolve('./package.json');
1336+
const contents = await readFile(filePath, { encoding: 'utf8' });
1337+
console.log(contents);
1338+
} catch (err) {
1339+
console.error(err.message);
1340+
}
1341+
}
1342+
logFile();
1343+
```
1344+
13161345
It is possible to abort an ongoing `readFile` using an {AbortSignal}. If a
13171346
request is aborted the promise returned is rejected with an `AbortError`:
13181347

0 commit comments

Comments
 (0)