Skip to content

Commit b55bbde

Browse files
clydinalan-agius4
authored andcommitted
refactor(@angular-devkit/build-angular): use async pipeline helper in HTML rewriting stream
The Node.js async `pipeline` helper function reduces the amount of infrastructure code needed to pipe HTML content through the parse5 transform stream.
1 parent ffeb3eb commit b55bbde

File tree

1 file changed

+11
-34
lines changed

1 file changed

+11
-34
lines changed

packages/angular_devkit/build_angular/src/utils/index-file/html-rewriting-stream.ts

Lines changed: 11 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@
66
* found in the LICENSE file at https://angular.io/license
77
*/
88

9-
import { Readable, Writable } from 'stream';
9+
import { Readable } from 'node:stream';
10+
import { pipeline } from 'node:stream/promises';
1011
import { loadEsmModule } from '../load-esm';
1112

1213
export async function htmlRewritingStream(content: string): Promise<{
@@ -16,42 +17,18 @@ export async function htmlRewritingStream(content: string): Promise<{
1617
const { RewritingStream } = await loadEsmModule<typeof import('parse5-html-rewriting-stream')>(
1718
'parse5-html-rewriting-stream',
1819
);
19-
const chunks: Buffer[] = [];
2020
const rewriter = new RewritingStream();
2121

2222
return {
2323
rewriter,
24-
transformedContent: () => {
25-
return new Promise((resolve) => {
26-
new Readable({
27-
encoding: 'utf8',
28-
read(): void {
29-
this.push(Buffer.from(content));
30-
this.push(null);
31-
},
32-
})
33-
.pipe(rewriter)
34-
.pipe(
35-
new Writable({
36-
write(
37-
chunk: string | Buffer,
38-
encoding: string | undefined,
39-
callback: Function,
40-
): void {
41-
chunks.push(
42-
typeof chunk === 'string'
43-
? Buffer.from(chunk, encoding as BufferEncoding)
44-
: chunk,
45-
);
46-
callback();
47-
},
48-
final(callback: (error?: Error) => void): void {
49-
callback();
50-
resolve(Buffer.concat(chunks).toString());
51-
},
52-
}),
53-
);
54-
});
55-
},
24+
transformedContent: () =>
25+
pipeline(Readable.from(content), rewriter, async function (source) {
26+
const chunks = [];
27+
for await (const chunk of source) {
28+
chunks.push(Buffer.from(chunk));
29+
}
30+
31+
return Buffer.concat(chunks).toString('utf-8');
32+
}),
5633
};
5734
}

0 commit comments

Comments
 (0)