How to Prevent CPU 100% When Using html-minifier in Node.js

This article explores the challenges of real‑time HTML and inline JS/CSS minification with html‑minifier in Node.js, including CPU‑spike bugs caused by malformed HTML, workarounds using the vm module with timeouts, performance optimizations, and future directions for faster, stable compression.

Node Underground
Node Underground
Node Underground
How to Prevent CPU 100% When Using html-minifier in Node.js

Reason

The author recently investigated real‑time compression of page HTML and inline JS/CSS. Initial attempts to scan and compress inline scripts within a front‑end module missed many cases, prompting a shift to full page HTML minification using the popular html-minifier module.

CPU 100%

Testing on a few pages showed good results, but a critical issue emerged: certain HTML fragments cause html-minifier to consume 100% CPU.

Example:

<!-- 使用 html-minifier 压缩导致 CPU 100% 案例 -->
<div style="background:url(\"FyueIVXXXXanapXXSutbFXXX.jpg\") no-repeat"></div>

The fragment contains malformed HTML; html-minifier relies on a proper syntax tree and fails to handle such input, leading to a CPU spike. The module’s author confirmed there is no plan to fix this limitation.

To avoid the issue, the author runs the minification inside a separate vm context with a timeout.

let vm = require('vm');
let sandbox = {
  minify: minify,
  config: config.minify,
  src: body
};
try {
  vm.runInNewContext('try{result=minify(src,config)}catch(e){err=e}', sandbox, {
    timeout: config.minifyTimeout
  });
} catch(err) {
  // ScriptTimeout exception – either a real timeout or an inline HTML/CSS compression error
  debug('html minify timeout.');
  return body;
}

This approach prevents the process from hanging; if the task exceeds the configured timeout, a ScriptTimeout exception is thrown instead of locking the CPU.

Note that Node.js’s vm module provides an isolated JavaScript execution context but not a separate OS process, so it is not process‑safe, yet it suffices to protect against CPU spikes caused by problematic HTML.

Non‑standard Exception Information

When html-minifier encounters certain malformed HTML, it throws a parse error as a plain string rather than an Error object, which can complicate error handling.

Example:

<p>hi
<!--

Developers must account for this non‑standard exception format when categorising or wrapping errors.

Slow Performance

Typical HTML minification takes 300‑500 ms, while page rendering often completes within 100 ms, making the overhead unacceptable for real‑time rendering scenarios.

To improve speed, the author applied two optimisations:

Disable less‑critical features, such as inline CSS compression, which saved roughly 100 ms per page.

Optimise memory usage to reduce garbage‑collection pauses; heavy GC in Node.js can increase minification time by 4‑5×.

Conclusion

The author resolved stability issues but not the fundamental performance bottleneck. Future work includes evaluating the newer minimize module, which promises better integration with production servers, though its JavaScript compression plugin is still under development.

The article’s purpose is to spark discussion and invite collaboration on building a fast, stable HTML compression module for the Node.js ecosystem.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

performancevmCPUhtml-minifierminification
Node Underground
Written by

Node Underground

No language is immortal—Node.js isn’t either—but thoughtful reflection is priceless. This underground community for Node.js enthusiasts was started by Taobao’s Front‑End Team (FED) to share our original insights and viewpoints from working with Node.js. Follow us. BTW, we’re hiring.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.