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

Node.js通过GET请求读取文件遇_dirname未定义问题及需求实现问询

问题解决与代码重构

核心错误:_dirname is not defined

你写错了变量名,正确的是**__dirname**(两个下划线)。如果你的项目使用ES模块(package.json中设置"type": "module"),Node.js默认不提供__dirname,需要手动构建:

import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

如果是默认的CommonJS模块,直接使用__dirname即可,注意必须是两个下划线。

完整功能实现(支持嵌套目录、错误状态码)

你的现有代码缺少HTTP服务器的核心逻辑,以下是重构后的完整代码,包含文件读取、错误处理、嵌套目录支持:

服务器代码(CommonJS版本)

const http = require('http');
const fs = require('fs');
const path = require('path');
const url = require('url');

const loadData = (folderPath) => {
  // 创建HTTP服务器实例
  const server = http.createServer((req, res) => {
    // 解析请求URL,提取文件名(去掉开头的/)
    const parsedUrl = url.parse(req.url);
    const fileName = parsedUrl.pathname.slice(1);

    // 安全拼接文件路径:项目根目录 + 指定文件夹 + 请求的文件名
    const fullPath = path.join(__dirname, folderPath, fileName);

    // 异步读取文件,避免阻塞事件循环
    fs.readFile(fullPath, (err, data) => {
      if (err) {
        if (err.code === 'ENOENT') {
          // 文件不存在,返回404状态码
          res.writeHead(404, { 'Content-Type': 'text/plain' });
          res.end('404 Not Found');
        } else {
          // 权限不足、路径非法等其他错误,返回500状态码
          res.writeHead(500, { 'Content-Type': 'text/plain' });
          res.end('500 Internal Server Error');
        }
        return;
      }

      // 文件读取成功,返回文件内容
      res.writeHead(200, { 'Content-Type': 'text/plain' });
      res.end(data);
    });
  });

  return server;
};

module.exports = loadData;

修正后的测试代码

const http = require('http');
const loadData = require('./server'); // 假设服务器代码存放在server.js中

const get = (file) => new Promise((resolve, reject) => {
  // 修正拼写错误:localost → localhost,statuc → status
  http.get(`http://localhost:3000/${file}`, res => {
    let data = "";
    let status = res.statusCode;
    
    res.on('data', chunk => {
      data += chunk;
    });
    
    res.on('end', () => {
      resolve({ data, status });
    });

    // 处理请求过程中的错误
    res.on('error', reject);
  });
});

const server = loadData('tmp/myapp/public');
const port = process.env.PORT || 3000;

// 服务器启动后再发起测试请求
server.listen(port, () => {
  console.log(`Server running on port ${port}`);
  get('myfile.txt').then(data => {
    console.log(data);
    server.close();
  }).catch(err => {
    console.error('Request failed:', err);
    server.close();
  });
});

关键功能说明

  • 嵌套目录支持:通过path.join安全拼接路径,可直接请求subdir/nested/file.txt这类嵌套路径的文件
  • 错误处理:精准区分文件不存在和其他服务器错误,返回对应HTTP状态码
  • 安全提示:当前代码已限制文件访问范围在指定的folderPath下,可额外添加路径校验逻辑,彻底避免路径遍历攻击(如请求../../etc/passwd)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 15:24:07