Не отображается картинка при отправке из Node.js в браузер

Я написал небольшой сервер для лэндинга. Он полностью работает, но выбивает ошибка при отправке изображения в запросе с браузера. Подскажите, пожалуйста, где ошибка.

// --------- Server.js

const http = require('http');
const routing = require('./routing');
const fs = require('fs');
const server = http.Server((req, res) => {
  routing.define(req, res);
}).listen(8000);

// --------- Index.is

const url = require('url');
const fs = require('fs');
const { request } = require('http');

const define = function(req, res) {
  let File__Path = (__dirname + "/main/index.html");
  fs.readFile(File__Path, 'utf-8', (err, html) => {
    res.writeHead(200, {
      "Content-Type": "text/html"
    });
    res.end(html);
  })
  const Url__Parsed = url.parse(req.url, true);
  let Path = Url__Parsed.pathname;
  
  if (/\./.test(Path)) {
    if (/\.css$/gi.test(Path)) {
      res.writeHead(200, {
        "Content-Type": "text/css"
      });
      let Read__Stream = fs.createReadStream(__dirname + "/static/css" + Path);
      Read__Stream.pipe(res);
      console.log("The Css file has gone!");
      return;
    } else if (/\.img$/gi.test(Path)) {
      res.writeHead(200, {
        "Content-Type": "image/img"
      });
      let Read__Stream = fs.createReadStream(__dirname + "/static/img" + Path);
      Read__Stream.pipe(res);
      console.log("The Img picture is off!");
      return;
    } else if (/\.svg$/gi.test(Path)) {
      res.writeHead(200, {
        "Content-Type": "image/svg"
      });
      let Read__Stream = fs.createReadStream(__dirname + "/static/img" + Path);
      Read__Stream.pipe(res);
      console.log("The Svg picture is off!");
      return;
    } else if (/\.jpeg$/gi.test(Path)) {
      res.writeHead(200, {
        "Content-Type": "image/jpeg"
      });
      let Read__Stream = fs.createReadStream(__dirname + "/static/img" + Path);
      Read__Stream.pipe(res);
      console.log("The Jpeg picture is off!");
      return;
    } else if (/\.jpg$/gi.test(Path)) { // The problem is here!!!
      res.writeHead(200, {
        "Content-Type": "image/jpg"
      });
      fs.createReadStream(__dirname + "/static/img/" + Path).pipe(res);
    } else if (/\.png$/gi.test(Path)) {
      res.writeHead(200, {
        "Content-Type": "image/png"
      });
      let Read__Stream = fs.createReadStream(__dirname + "/static/img" + Path);
      Read__Stream.pipe(res);
      console.log("The Png picture is off!");
    } else if (/\.js$/gi.test(Path)) {
      res.writeHead(200, {
        "Content-Type": "application/javascript"
      });
      let Read__Stream = fs.createReadStream(__dirname + "/static/js" + Path);
      Read__Stream.pipe(res);
      return;
    }
  }
};

exports.define = define;

Браузер:

введите сюда описание изображения


Ответы (1 шт):

Автор решения: Ein

Есть две основные проблемы из-за которых не отдаётся картинка.

  1. В слюбом случает отдаётся html и завершается соединение.

    const define = function(req, res) {
        let File__Path = (__dirname + "/main/index.html");
        /* В любом случае происходит чтение файла */
        fs.readFile(File__Path, 'utf-8', (err, html) => {
            res.writeHead(200, {
                "Content-Type": "text/html"
            });
            /* Вот тут мы завершаем вывод */
            res.end(html);
        })
        const Url__Parsed = url.parse(req.url, true);
        let Path = Url__Parsed.pathname;
        /* ... */
    
    };
    
  2. Лишнее "/static/img"

    if (/\.jpg$/gi.test(Path)) {
        res.writeHead(200, {
            "Content-Type": "image/jpg"
        });
        // Получается что-то вроде: /tmp/static/img//static/img/asd.jpg
        // Хотя правильный путь:    /tmp/static/img/asd.jpg
        fs.createReadStream(__dirname + "/static/img" + Path).pipe(res);
    }
    
→ Ссылка