由于我对 Nodejs 的自学仍在继续,我当然正在努力完成一些任务,我再次来到 SO 寻求帮助。 我打算创建一个任务来读取特定文件夹内的文件夹,其中每个文件夹都有一个 index.html 文件。 因此,当查找 index.html 文件时,它将将该文件的路径作为链接传递给
<ul><li><a href="to the folder where the index.html is located">./mainFolder/subfolder/index.html</a></li></ul>
基本上,我开始触及这项任务的表面,但现在我陷入了困境。
/////////////create list of links
const path = require('path');
const fs = require('fs');
//joining path of directory
const directoryPath = path.join(__dirname, './dist/mainFolder');
//passing directoryPath and callback function
fs.readdir(directoryPath, function (err, files) {
//handling error
if (err) {
return console.log('Unable to scan directory: ' + err);
}
//listing all files using forEach
files.forEach(function (file) {
var listLinks = [file]
var mainInd = './dist/mainFolder';
mainInd.ul = document.createElement('ul');
var l;
mainInd.document.getElementById('previewList').appendChild(ul);
listLinks.forEach(renderLinkList);
function renderLinkList(element) {
var li = document.createElement('li');
//var a = document.createElement('a');
//a.setAttribute('href', 'https://www.mypage.com');
//li.setAttribute('class','item');
ul.appendChild(li);
//li.appendChild(a);
l = (document.createTextNode(element));
li.innerHTML=li.innerHTML;}console.log(file); });});
任何帮助将不胜感激。
亲切的问候,
费尔南多
最佳答案
您可以使用以下代码 -
- 读取主文件夹内的所有文件和文件夹
- 迭代文件和文件夹
- 跳过所有文件
- 最后在所有子文件夹中构建index.html文件的文件路径
此代码片段打印index.html 文件的绝对文件路径。
如果需要,您也可以将其设置为相对文件路径。
const path = require("path");
const fs = require("fs");
const index_files = [];
const parent_directory_path = "";
const directoryPath = path.join(__dirname, parent_directory_path);
fs.readdir(directoryPath, function (error, files) {
if (!error) {
files.forEach(function (file) {
const currDirectoryPath = path.join(__dirname, file);
if (fs.existsSync(currDirectoryPath) && fs.lstatSync(currDirectoryPath).isDirectory()) {
index_files.push(currDirectoryPath + "/index.html");
}
});
console.log(index_files);
}
});
更新
由于fs.readdir
API提供了主文件夹内的所有文件和文件夹,因此我们需要一个条件来跳过文件。
fs.existsSync(currDirectoryPath) && fs.lstatSync(currDirectoryPath).isDirectory()
检查当前文件/文件夹是否存在并且是文件夹。
此代码片段还假设父目录是当前目录。如果您想提供不同的父目录路径,请在 parent_directory_path
变量中设置父目录路径值。
关于javascript - 如何读取文件夹内的文件夹并从每个文件夹获取 index.html 并作为列表 (li) 标记中的链接传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60449712/