由于我使用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); });});
任何帮助都将不胜感激。
问候,
Fernando
您可以使用以下代码-
- 读取所有文件&主文件夹中的文件夹
- 遍历文件&文件夹
- 跳过所有文件
- 最后在所有子文件夹中构造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
变量中设置父目录路径值。