Node.js读取子文件夹index.html并生成链接列表求助
Hey Fernando, let's fix up your Node.js script to generate that link list you need! I noticed a few key issues in your original code that are causing the bottleneck—let's break them down and build a working solution together.
First, the core problems in your current code:
- Node.js doesn't have browser DOM APIs: You're trying to use
document.createElement,getElementById, etc., but those only exist in web browsers. Node.js is a backend runtime, so we can't manipulate DOM elements directly like that. - No directory validation: You're looping through all items in the folder but not checking if they're actually subfolders (you might end up trying to process regular files too).
- No check for
index.html: Your code doesn't verify if each subfolder actually contains anindex.htmlfile. - Variable logic issues: You're treating strings like
mainIndas objects and trying to add properties to them, which won't work.
Here's a working synchronous solution (great for small to medium folders):
This script will scan your target folder, validate subfolders with index.html, and generate the HTML list you need (saving it to an output file):
const path = require('path'); const fs = require('fs'); // Define the target main folder const mainFolderPath = path.join(__dirname, './dist/mainFolder'); try { // Read all items in the main folder const folderItems = fs.readdirSync(mainFolderPath); let linkListHtml = '<ul>'; folderItems.forEach(item => { const itemFullPath = path.join(mainFolderPath, item); const itemStats = fs.statSync(itemFullPath); // Only process directories (subfolders) if (itemStats.isDirectory()) { const indexHtmlPath = path.join(itemFullPath, 'index.html'); // Check if index.html exists in this subfolder if (fs.existsSync(indexHtmlPath)) { // Generate a relative path for the href (adjust this if needed for your use case) const relativeLinkPath = path.relative(__dirname, indexHtmlPath); // Add the list item with link linkListHtml += `<li><a href="${relativeLinkPath}">${relativeLinkPath}</a></li>`; } } }); linkListHtml += '</ul>'; // Save the generated HTML to a file (you can also use this string in a web response) const outputFilePath = path.join(__dirname, 'link-list.html'); fs.writeFileSync(outputFilePath, linkListHtml); console.log(`Success! Link list saved to ${outputFilePath}`); } catch (error) { console.error('Error generating link list:', error); }
If you need an asynchronous version (better for large folders to avoid blocking):
Using fs.promises keeps things non-blocking, which is better practice for larger directory structures:
const path = require('path'); const fs = require('fs').promises; async function generateLinkList() { const mainFolderPath = path.join(__dirname, './dist/mainFolder'); let linkListHtml = '<ul>'; try { const folderItems = await fs.readdir(mainFolderPath); for (const item of folderItems) { const itemFullPath = path.join(mainFolderPath, item); const itemStats = await fs.stat(itemFullPath); if (itemStats.isDirectory()) { const indexHtmlPath = path.join(itemFullPath, 'index.html'); // Check if index.html exists (using fs.access which throws if not found) try { await fs.access(indexHtmlPath); const relativeLinkPath = path.relative(__dirname, indexHtmlPath); linkListHtml += `<li><a href="${relativeLinkPath}">${relativeLinkPath}</a></li>`; } catch { // Skip subfolders without index.html continue; } } } linkListHtml += '</ul>'; const outputFilePath = path.join(__dirname, 'link-list.html'); await fs.writeFile(outputFilePath, linkListHtml); console.log(`Success! Link list saved to ${outputFilePath}`); } catch (error) { console.error('Error generating link list:', error); } } // Run the function generateLinkList();
How to use this:
- Save either script in your project directory
- Run it with
node your-script-name.js - It will create a
link-list.htmlfile with your formatted<ul><li>link list
If you need to inject this list into an existing HTML page (like one with a previewList element), you can:
- Read your existing HTML file
- Replace the content inside the
previewListelement with the generatedlinkListHtmlstring - Write the modified content back to the HTML file
Let me know if you need help adapting this to your specific use case!
内容的提问来源于stack exchange,提问作者Fernando Fas
相关产品推荐
相关产品推荐

