Skip to content

Commit 72cf799

Browse files
committed
refactor(@angular/pwa): use stream pipeline operator with HTML rewriter
The index HTML augmentation within the PWA schematic now uses the Node.js promise-based pipeline helper to reduce the complexity of the code when using the parse5 streaming rewriter. This removes a noticeable amount of code as well as removing the need to manually wrap the result in a Promise.
1 parent 10641be commit 72cf799

File tree

1 file changed

+9
-29
lines changed

1 file changed

+9
-29
lines changed

packages/angular/pwa/pwa/index.ts

Lines changed: 9 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -20,15 +20,13 @@ import {
2020
} from '@angular-devkit/schematics';
2121
import { readWorkspace, writeWorkspace } from '@schematics/angular/utility';
2222
import { posix } from 'path';
23-
import { Readable, Writable } from 'stream';
23+
import { Readable } from 'stream';
24+
import { pipeline } from 'stream/promises';
2425
import { Schema as PwaOptions } from './schema';
2526

2627
function updateIndexFile(path: string): Rule {
2728
return async (host: Tree) => {
28-
const buffer = host.read(path);
29-
if (buffer === null) {
30-
throw new SchematicsException(`Could not read index file: ${path}`);
31-
}
29+
const originalContent = host.readText(path);
3230

3331
const { RewritingStream } = await loadEsmModule<typeof import('parse5-html-rewriting-stream')>(
3432
'parse5-html-rewriting-stream',
@@ -57,30 +55,12 @@ function updateIndexFile(path: string): Rule {
5755
rewriter.emitEndTag(endTag);
5856
});
5957

60-
return new Promise<void>((resolve) => {
61-
const input = new Readable({
62-
encoding: 'utf8',
63-
read(): void {
64-
this.push(buffer);
65-
this.push(null);
66-
},
67-
});
68-
69-
const chunks: Array<Buffer> = [];
70-
const output = new Writable({
71-
write(chunk: string | Buffer, encoding: BufferEncoding, callback: Function): void {
72-
chunks.push(typeof chunk === 'string' ? Buffer.from(chunk, encoding) : chunk);
73-
callback();
74-
},
75-
final(callback: (error?: Error) => void): void {
76-
const full = Buffer.concat(chunks);
77-
host.overwrite(path, full.toString());
78-
callback();
79-
resolve();
80-
},
81-
});
82-
83-
input.pipe(rewriter).pipe(output);
58+
return pipeline(Readable.from(originalContent), rewriter, async function (source) {
59+
const chunks = [];
60+
for await (const chunk of source) {
61+
chunks.push(Buffer.from(chunk));
62+
}
63+
host.overwrite(path, Buffer.concat(chunks));
8464
});
8565
};
8666
}

0 commit comments

Comments
 (0)