Skip to content
Open
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
48 changes: 34 additions & 14 deletions src/nodes/html.ts
Original file line number Diff line number Diff line change
Expand Up @@ -327,21 +327,41 @@ export default class HTMLElement extends Node {
.replace(/\s+$/, ''); // trimRight;
}

public toString() {
const tag = this.rawTagName;
if (tag) {
const attrs = this.rawAttrs ? ` ${this.rawAttrs}` : '';
return this.voidTag.formatNode(tag, attrs, this.innerHTML);
public toString(): string {
return this.serialize([this]);
}

public get innerHTML(): string {
return this.serialize(this.childNodes);
}

// Iterative, so that deeply nested trees do not overflow the call stack
private serialize(nodes: Node[]): string {
const out: string[] = [];
const stack: (Node | string)[] = [...nodes].reverse();
while (stack.length > 0) {
const item = stack.pop();
if (typeof item === 'string') {
out.push(item);
} else if (item instanceof HTMLElement) {
const tag = item.rawTagName;
if (tag) {
const attrs = item.rawAttrs ? ` ${item.rawAttrs}` : '';
if (item.voidTag.isVoidElement(tag.toLowerCase())) {
out.push(item.voidTag.formatNode(tag, attrs, ''));
continue;
}
out.push(`<${tag}${attrs}>`);
stack.push(`</${tag}>`);
}
for (let i = item.childNodes.length - 1; i >= 0; i--) {
stack.push(item.childNodes[i]);
}
} else {
out.push(item.toString());
}
}
return this.innerHTML;
}

public get innerHTML() {
return this.childNodes
.map((child) => {
return child.toString();
})
.join('');
return out.join('');
}

public set innerHTML(content: string) {
Expand Down
19 changes: 19 additions & 0 deletions test/tests/issues/324.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
const { parse } = require('@test/test-target');

// https://github.com/taoqf/node-html-parser/issues/324
describe('issue 324 toString of deeply nested html', function () {
it('serializes deep nesting without overflowing the stack', function () {
const depth = 10000;
const html = '<div>'.repeat(depth) + 'x' + '</div>'.repeat(depth);
const root = parse(html);
root.toString().should.eql(html);
root.firstChild.outerHTML.should.eql(html);
root.innerHTML.should.eql(html);
});
it('keeps void tags, comments and attributes', function () {
const html = '<p class="a">x<br><!-- c --><img src="i.png"><span>y</span></p>';
const root = parse(html, { comment: true });
root.toString().should.eql(html);
root.firstChild.innerHTML.should.eql('x<br><!-- c --><img src="i.png"><span>y</span>');
});
});