Skip to content
Closed
Show file tree
Hide file tree
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
Prev Previous commit
fs: add FileHandle.prototype.text method
  • Loading branch information
aduh95 committed Sep 6, 2021
commit 109bf7e32ea77c85c574e78dedf66ba8c75d62ba
11 changes: 11 additions & 0 deletions doc/api/fs.md
Original file line number Diff line number Diff line change
Expand Up @@ -426,6 +426,17 @@ Request that all data for the open file descriptor is flushed to the storage
device. The specific implementation is operating system and device specific.
Refer to the POSIX fsync(2) documentation for more detail.

#### `filehandle.text()`
<!-- YAML
added: REPLACEME
-->

> Stability: 1 - Experimental

* Returns: {Promise} Fulfills with a {string} upon success.

Reads the whole file as UTF-8 text.

#### `filehandle.truncate(len)`
<!-- YAML
added: v10.0.0
Expand Down
4 changes: 4 additions & 0 deletions lib/internal/fs/promises.js
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,10 @@ class FileHandle extends EventEmitterMixin(JSTransferable) {
return buffer.buffer;
}

text() {
return this.readFile({ encoding: 'utf8' });
Copy link
Copy Markdown
Member

@ronag ronag Sep 7, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

toUSVString?

}

[kTransfer]() {
if (this[kClosePromise] || this[kRefs] > 1) {
throw lazyDOMException('Cannot transfer FileHandle while in use',
Expand Down
30 changes: 30 additions & 0 deletions test/parallel/test-fs-promises-file-handle-text.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
'use strict';

const common = require('../common');

// The following tests validate FileHandle.prototype.text method.

const fs = require('fs');
const { open } = fs.promises;
const path = require('path');
const tmpdir = require('../common/tmpdir');
const assert = require('assert');
const tmpDir = tmpdir.path;

tmpdir.refresh();

(async () => {
const data = 'Hello World!';
const filePath = path.resolve(tmpDir, 'text');
fs.writeFileSync(filePath, data);

let fileHandle;
try {
fileHandle = await open(filePath);

const fileContent = await fileHandle.text();
assert.strictEqual(fileContent, data);
} finally {
await fileHandle?.close();
}
})().then(common.mustCall());