Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

doc: add fsPromises.readFile() example #40237

Merged
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions doc/api/fs.md
Original file line number Diff line number Diff line change
Expand Up @@ -1147,6 +1147,32 @@ 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:
bnb marked this conversation as resolved.
Show resolved Hide resolved
```mjs
import { readFile } from 'fs/promises';
bnb marked this conversation as resolved.
Show resolved Hide resolved
try {
const contents = await readFile(new URL('./package.json', import.meta.url), { encoding: 'utf8' });
bnb marked this conversation as resolved.
Show resolved Hide resolved

bnb marked this conversation as resolved.
Show resolved Hide resolved
console.log(contents);
} catch (err) {
console.error(err.message);
}
```

```cjs
const { readFile } = require('fs/promises');
const { resolve } = require('path');
bnb marked this conversation as resolved.
Show resolved Hide resolved
async function logFile() {
try {
const contents = await readFile(resolve('./package.json'), { encoding: 'utf8' });
bnb marked this conversation as resolved.
Show resolved Hide resolved
console.log(contents);
} catch (err) {
console.error(err.message);
}
}
logFile();
bnb marked this conversation as resolved.
Show resolved Hide resolved
```

It is possible to abort an ongoing `readFile` using an {AbortSignal}. If a
request is aborted the promise returned is rejected with an `AbortError`:

Expand Down