![](/img/trans.png)
[英]How do I serve a .ttf file in node.js using the http and fs libraries?
[英]How do I serve ALL images using Node.js
我想学习如何在不使用Express之类的框架的情况下使用Node.js提供所有图像。 我最终将使用Express,但是我想学习如何工作。
此解决方案之前已经回答了这个问题:
fs = require('fs');
http = require('http');
url = require('url');
http.createServer(function(req, res){
var request = url.parse(req.url, true);
var action = request.pathname;
if (action == '/logo.gif') {
var img = fs.readFileSync('./logo.gif');
res.writeHead(200, {'Content-Type': 'image/gif' });
res.end(img, 'binary');
} else {
res.writeHead(200, {'Content-Type': 'text/plain' });
res.end('Hello World \n');
}
}).listen(8080, '127.0.0.1');
这种解决方案似乎只能处理一个图像,我不想为我拥有的每个图像编写代码。 有更好的解决方案吗?
如何提供文件夹中的所有图像?
我当时在想有没有一种方法可以检查请求的扩展名? 例如,如果请求结尾处带有.png,则检查images文件夹并使用正确的内容类型image / png?
最简单的解决方法是:
if (/.gif$/i.test(action)) {
var img = fs.readFileSync(action);
res.writeHead(200, {'Content-Type': 'image/gif' });
res.end(img, 'binary');
}
尽管我强烈建议使用和/或学习connect.static中间件的源代码。 这就是Express本身的用途。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.