You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript与Node.js加载HTML为document并批量操作多文件?

Batch HTML Generation & Manipulation with Node.js Using DOM-like APIs

Absolutely, this approach is totally feasible and a go-to pattern for batch processing HTML files in Node.js! Since Node.js doesn’t natively include browser DOM APIs like document, we’ll use a library called jsdom to simulate that environment—letting you use familiar vanilla JavaScript to manipulate your templates just like you would in a browser.

Step 1: Set Up Dependencies

First, install jsdom (the most popular library for simulating browser DOM in Node.js) and use Node’s built-in fs/promises for clean async file operations:

npm install jsdom

Step 2: Prepare Your Template & Data List

Make sure your model.html has clear targets for data injection—like empty elements with specific IDs, or placeholder text such as {{pageTitle}}. Then define your list of target files and their corresponding data:

const targetFiles = [
  { filename: "home.html", data: { title: "Home Page", content: "Welcome to our website!" } },
  { filename: "services.html", data: { title: "Our Services", content: "We offer top-tier digital solutions." } },
  { filename: "contact.html", data: { title: "Get In Touch", content: "Reach out to us for inquiries." } }
];

Step 3: Write the Batch Processing Script

Here’s a complete script that reads your template, loops through your data list, manipulates each instance as a document object, and writes the final HTML files:

const fs = require('fs/promises');
const { JSDOM } = require('jsdom');

async function generateHTMLFiles() {
  try {
    // Read the template file once
    const templateHTML = await fs.readFile('./model.html', 'utf8');

    // Process each target file in sequence
    for (const entry of targetFiles) {
      // Create a DOM instance from the template
      const dom = new JSDOM(templateHTML);
      const document = dom.window.document;

      // Manipulate the DOM with vanilla JS
      // Update page title
      document.title = entry.data.title;
      // Update heading element
      const pageHeading = document.querySelector('#page-heading');
      if (pageHeading) pageHeading.textContent = entry.data.title;
      // Update main content
      const mainContent = document.querySelector('#main-content');
      if (mainContent) mainContent.textContent = entry.data.content;

      // Convert the modified DOM back to HTML string
      const finalHTML = dom.serialize();

      // Write to the target file
      await fs.writeFile(`./${entry.filename}`, finalHTML, 'utf8');
      console.log(`✅ Generated ${entry.filename}`);
    }
  } catch (error) {
    console.error('❌ Error processing files:', error);
  }
}

// Run the batch process
generateHTMLFiles();

Key Tips for Smooth Workflows

  • DOM Flexibility: You can use any vanilla JS DOM method you’re familiar with—querySelectorAll, appendChild, setAttribute, etc.—just like in a browser.
  • Lighter Alternatives: If you only need simple manipulations, try cheerio (a jQuery-like library that’s faster than jsdom but doesn’t fully simulate the browser DOM).
  • Complex Templating: For logic-heavy templates (like conditionals or loops), pair jsdom with a templating engine like EJS, or use placeholder strings that you replace directly in the HTML.
  • Performance: For large batches (100+ files), use a concurrency limiter like p-limit to avoid overwhelming your file system.

Is This Approach Valid?

100% yes! This method lets you leverage existing DOM knowledge instead of learning a new templating language, and it’s perfect for maintaining consistency across multiple pages in batch workflows.

内容的提问来源于stack exchange,提问作者neolith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:15:06