GeezerVison is showing github.com — doc: add fsPromises.readFile() example · nodejs/node@ce3cb29
File tree
Expand file treeCollapse file tree
Open diff view settings
Expand file treeCollapse file tree
Open diff view settings
Collapse file
Copy file name to clipboardExpand all lines: doc/api/fs.md +29Lines changed: 29 additions & 0 deletions - Display the source diff
- Display the rich diff
| Original file line number | Diff line number | Diff line change |
|---|
@@ -1307,6 +1307,35 @@ platform-specific. On macOS, Linux, and Windows, the promise will be rejected |
1307 | 1307 | with an error. On FreeBSD, a representation of the directory's contents will be |
1308 | 1308 | returned. |
1309 | 1309 |
|
| 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 | +
|
1310 | 1339 | It is possible to abort an ongoing `readFile` using an {AbortSignal}. If a |
1311 | 1340 | request is aborted the promise returned is rejected with an `AbortError`: |
1312 | 1341 |
|
|