From ce3cb29319fb37ee74484b5c09ee938942568d89 Mon Sep 17 00:00:00 2001 From: Tierney Cyren Date: Tue, 11 Oct 2022 05:35:36 +0200 Subject: [PATCH] doc: add fsPromises.readFile() example Signed-off-by: Tierney Cyren PR-URL: https://github.com/nodejs/node/pull/40237 Reviewed-By: James M Snell Reviewed-By: Antoine du Hamel --- doc/api/fs.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/doc/api/fs.md b/doc/api/fs.md index 3e5ff52986163a..e0ea18eb11c12c 100644 --- a/doc/api/fs.md +++ b/doc/api/fs.md @@ -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`: