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

无需Express在Node.js中实现动态文件路由及目录文件展示

无Express环境下Node.js实现文件路由(目录特殊格式展示)

核心问题出在你用了根路径/${element}调用fs.statSync,但你的文件和目录都在当前脚本的执行目录下,根路径根本找不到对应资源,这就是报错的原因。

直接用下面修正后的代码就能解决问题:

const fs = require('fs');
const path = require('path'); // 引入path模块处理路径更可靠

// 假设这是http.createServer的回调函数内部代码
if (path === '/' && method === 'GET') {
    const currentDir = './';
    const dirItems = fs.readdirSync(currentDir, { encoding: 'utf-8' });
    response.writeHead(200, { 'Content-Type': 'text/html' });
    
    response.write('<ul style="list-style-type: none; padding-left: 0;">');
    dirItems.forEach(item => {
        // 用path.join拼接路径,避免手动拼接出现的分隔符问题
        const itemPath = path.join(currentDir, item);
        const stats = fs.statSync(itemPath);
        const displayName = stats.isDirectory() ? `.../${item}` : item;
        
        response.write(`<li><a href="./${item}" style="text-decoration: none; margin: 4px 0; display: block;">${displayName}</a></li>`);
    });
    response.write('</ul>');
    return response.end();
}

关键修改说明

  • 修正路径错误:用path.join拼接当前目录和条目名称,替代硬编码的根路径,确保能正确读取本地资源状态
  • 语义化遍历:用forEach替代map,因为这里只是遍历输出内容,不需要返回新数组
  • 规范HTML结构:补充了完整的<ul>容器,还加了点基础样式让列表更美观
  • 显式状态码:直接设置200状态码,避免依赖默认值带来的不确定性

额外优化建议

  1. 改用异步API:同步的readdirSync和statSync会阻塞事件循环,如果目录内容很多,建议换成fs.promises的异步版本:
const dirItems = await fs.promises.readdir(currentDir, { encoding: 'utf-8' });
// 遍历的时候用Promise.all处理stat请求
const statsList = await Promise.all(dirItems.map(item => fs.promises.stat(path.join(currentDir, item))));
  1. 过滤隐藏文件:可以加个过滤条件,把以.开头的隐藏文件/目录排除:
const dirItems = fs.readdirSync(currentDir, { encoding: 'utf-8' }).filter(item => !item.startsWith('.'));
  1. 错误捕获:给statSync加try-catch,避免因为权限问题或者资源被删除导致服务崩溃:
try {
    const stats = fs.statSync(itemPath);
    // ... 生成HTML代码
} catch (err) {
    console.error(`读取${item}状态失败:`, err);
    response.write(`<li>${item} (无法访问)</li>`);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 01:11:32