Skip to content

Commit ce3cb29

Browse files
bnbdanielleadams
authored andcommitted
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 97df9b8 commit ce3cb29

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
@@ -1307,6 +1307,35 @@ platform-specific. On macOS, Linux, and Windows, the promise will be rejected
13071307
with an error. On FreeBSD, a representation of the directory's contents will be
13081308
returned.
13091309
1310+
An example of reading a `package.json` file located in the same directory of the
1311+
running code:
1312+
1313+
```mjs
1314+
import { readFile } from 'node:fs/promises';
1315+
try {
1316+
const filePath = new URL('./package.json', import.meta.url);
1317+
const contents = await readFile(filePath, { encoding: 'utf8' });
1318+
console.log(contents);
1319+
} catch (err) {
1320+
console.error(err.message);
1321+
}
1322+
```
1323+
1324+
```cjs
1325+
const { readFile } = require('node:fs/promises');
1326+
const { resolve } = require('node:path');
1327+
async function logFile() {
1328+
try {
1329+
const filePath = resolve('./package.json');
1330+
const contents = await readFile(filePath, { encoding: 'utf8' });
1331+
console.log(contents);
1332+
} catch (err) {
1333+
console.error(err.message);
1334+
}
1335+
}
1336+
logFile();
1337+
```
1338+
13101339
It is possible to abort an ongoing `readFile` using an {AbortSignal}. If a
13111340
request is aborted the promise returned is rejected with an `AbortError`:
13121341

0 commit comments

Comments
 (0)