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

FS promises: handle long files reading #19643

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
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
14 changes: 8 additions & 6 deletions lib/fs/promises.js
Original file line number Diff line number Diff line change
Expand Up @@ -147,15 +147,17 @@ async function readFileHandle(filehandle, options) {

const chunks = [];
const chunkSize = Math.min(size, 16384);
const buf = Buffer.alloc(chunkSize);
let totalRead = 0;
let endOfFile = false;
do {
const buf = Buffer.alloc(chunkSize);
const { bytesRead, buffer } =
await read(filehandle, buf, 0, buf.length);
totalRead = bytesRead;
if (totalRead > 0)
chunks.push(buffer.slice(0, totalRead));
} while (totalRead === chunkSize);
await read(filehandle, buf, 0, chunkSize, totalRead);
totalRead += bytesRead;
endOfFile = bytesRead !== chunkSize;
if (bytesRead > 0)
chunks.push(buffer.slice(0, bytesRead));
} while (!endOfFile);

const result = Buffer.concat(chunks);
if (options.encoding) {
Expand Down
28 changes: 28 additions & 0 deletions test/parallel/test-fs-promises-read-file.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
'use strict';

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

const assert = require('assert');
const path = require('path');
const { writeFile, readFile } = require('fs/promises');
const tmpdir = require('../common/tmpdir');
tmpdir.refresh();

const fn = path.join(tmpdir.path, 'large-file');

common.crashOnUnhandledRejection();

// Creating large buffer with random content
const buffer = Buffer.from(
Copy link
Member

Choose a reason for hiding this comment

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

You can generate this buffer with crypto.randomBytes(16834 * 2) actually, but the current method LGTM anyway.

Array.apply(null, { length: 16834 * 2 })
.map(Math.random)
.map((number) => (number * (1 << 8)))
);

// Writing buffer to a file then try to read it
writeFile(fn, buffer)
.then(() => readFile(fn))
.then((readBuffer) => {
assert.strictEqual(readBuffer.equals(buffer), true);
})
.then(common.mustCall());