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 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
27 changes: 27 additions & 0 deletions doc/api/fs.md
Expand Up @@ -1147,6 +1147,33 @@ 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 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('fs/promises');
const { resolve } = require('path');
bnb marked this conversation as resolved.
Show resolved Hide resolved
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();
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