Skip to content

Commit 32b2184

Browse files
jesseskinnerkjmph
authored andcommitted
Stream data when writing files consistently in prerender
1 parent bf44149 commit 32b2184

File tree

1 file changed

+21
-28
lines changed

1 file changed

+21
-28
lines changed

packages/kit/src/core/adapt/prerender.js

Lines changed: 21 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,25 @@ export async function prerender({ cwd, out, log, config, build_data, fallback, a
142142
return path;
143143
}
144144

145+
/**
146+
* @param {string} file
147+
* @param {unknown} body
148+
*/
149+
async function writeBodyToFile(file, body) {
150+
if (
151+
body && typeof body === 'object' &&
152+
typeof body[Symbol.asyncIterator] === 'function'
153+
) {
154+
const output_stream = createWriteStream(file);
155+
const data = Readable.from(body);
156+
data.on('error', () => output_stream.end());
157+
data.pipe(output_stream);
158+
await new Promise((resolve) => output_stream.on('finish', resolve));
159+
} else {
160+
writeFileSync(file, body);
161+
}
162+
}
163+
145164
/**
146165
* @param {string} decoded_path
147166
* @param {string?} referrer
@@ -207,22 +226,7 @@ export async function prerender({ cwd, out, log, config, build_data, fallback, a
207226

208227
if (rendered.status === 200) {
209228
log.info(`${rendered.status} ${path}`);
210-
211-
if (
212-
rendered.body &&
213-
typeof rendered.body === 'object' &&
214-
typeof rendered.body[Symbol.asyncIterator] === 'function'
215-
) {
216-
let body = '';
217-
218-
for await (const chunk of rendered.body) {
219-
body += chunk;
220-
}
221-
222-
writeFileSync(file, body);
223-
} else {
224-
writeFileSync(file, rendered.body || '');
225-
}
229+
await writeBodyToFile(file, rendered.body || '');
226230
written_files.push(file);
227231
} else if (response_type !== OK) {
228232
error({ status: rendered.status, path, referrer, referenceType: 'linked' });
@@ -242,18 +246,7 @@ export async function prerender({ cwd, out, log, config, build_data, fallback, a
242246
mkdirp(dirname(file));
243247

244248
if (result.body) {
245-
if (
246-
typeof result.body === 'object' &&
247-
typeof result.body[Symbol.asyncIterator] === 'function'
248-
) {
249-
const output_stream = createWriteStream(file);
250-
const data = Readable.from(result.body);
251-
data.on('error', () => output_stream.end());
252-
data.pipe(output_stream);
253-
await new Promise((resolve) => output_stream.on('finish', resolve));
254-
} else {
255-
writeFileSync(file, result.body);
256-
}
249+
await writeBodyToFile(file, result.body);
257250
written_files.push(file);
258251
}
259252

0 commit comments

Comments
 (0)