使用 fs 显示 html 图像

Displaying html with images using fs

我需要在我的服务器中显示一个 html 包含 一些文本和东西,这些在这里并不重要,第一张图片 在作为参数 给出的文件夹内找到

我找到了另一个答案,其中 fs.readFile 用于直接检索 html 文件,图像已经在那里,但在这种情况下 我需要构建一个 html 每张图片.

我试过了,但没有显示任何图像:

var http = require('http');
const fs = require('fs');

function read_dir(req, res, path="./images") {
    
    let image_urls = fs.readdirSync(path);
    let src = path.split("").slice(1).join("");

    let image = `<img id="image" src="http://localhost:8888${src}/${image_urls[0]}">`;
 
    res.end(image);
}

function onrequest(request, response) {
    // Programs what is going to be sent back to the browser.
    console.log("HTTP request received");

    // Parses command line arguments
    var myArgs = process.argv.slice(2);

    response.writeHead(200, 
        {"Content-Type": 'text/html'}
    );
    response.write(`<h1>SLIDESHOW AREA</h1>`);

    read_dir(request, response, myArgs[0]);
}

// The http.createServer() method turns my computer into an HTTP server.
var server = http.createServer(onrequest);

// The server.listen() method creates a listener on the specified port or path.
// server.listen(port, hostname, backlog, callback);
server.listen(8888);

console.log("Listening on http://localhost:8888/");

此标签 <img id="image" src="http://localhost:8888${src}/${image_urls[0]}"> 正在尝试访问您的服务器 "http://localhost:8888${src}/${image_urls[0]}" url。

因此您需要为浏览器提供服务才能下载它。

jpeg 图像由 'Content-type: image/jpeg'header 提供,但对于大图像,您需要进行更复杂的工作,例如缓存内存、流媒体等;否则你的页面加载时间会很容易下降。

推荐使用cloudinary等服务来提供此类内容。

好的,所以我发现缺少了什么。如果您像我一样对服务器了解得非常差,这可能会有所帮助。

<img src="http://localhost:8888/image/jpeg/campus1.jpg">

服务器读取图片src时,发送GET请求url /image/jpeg/campus1.jpg。现在服务器可以显示 HTML 元素,但不能显示 JPEG 元素,这是这里的基础。

这真的很微妙,图像必须从其文件夹中读取,并在显示之前正确设置。

因此,正确的做法是在服务器内部创建一个路由来读取图像并告诉服务器它们是 'image/jpeg' 类型。到那时,图像已准备就绪并被烘烤以供 HTML.

读取
var http = require('http');
const fs = require('fs');

let routes = { "/": main, "/image": fileRouter }

function main(req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});

    res.write("<h1>HI</h1>");
    res.write("<h2>Here's an image</h2>");
    res.end(`<img src="http://localhost:8888/image/jpeg/campus1.jpg">`);
}

function fileRouter(req, res) {
    let path = req.url;
    console.log(path);

    fs.readFile("."+path, function(err, data) {
        if(err) {
            res.writeHead(500, { 'Content-Type' : 'text/plain' });
            res.end('500 - Internal Error');
        } else {
            res.writeHead(200, { 'Content-Type' : 'image/jpeg' });
            res.end(data);
        }
    });
}

function onrequest(req, res) {
    //Parse Request
    let url = req.url;
    let route = url.split("/")[1];
    console.log(req.method, req.url);
    
    //Route Request
    if (typeof routes["/" + route] === 'function') { 
        routes["/" + route](req, res);
    } else {
        res.writeHead(404); //not found
        res.end();
    }
}

var server = http.createServer(onrequest);

server.listen(8888);

我希望编程不会总是需要我的脑袋被撞开,事情并不总是有意义的,我有时不明白为什么人们会这样设计东西。但是,爱并不总是那么容易。祝大家有个愉快的一天!