企业网站内容建设 知乎/重庆网站排名公司
本篇文章介绍如何搭建图片文件服务器,用户可以在浏览器请求访问浏览该图片。
/*** 图片服务器搭建*///载入http模块
const http = require("http");
//载入fs模块
const fs = require("fs");
//载入path模块
const path = require("path");
//载入url模块
const url = require("url");
//载入zlib模块
const zlib = require("zlib");//当前目录名
var curDir = "";//服务器创建
const server = http.createServer(function(req,res){//定义mime对象设置相应的响应头类型var mime = {".jpeg":"image/jpeg",".jpg":"image/jpg",".png":"image/png",".tiff":"image/tiff",".pdf":"application/pdf"};//获取请求url并转换请求路径var pathName = url.parse(req.url).pathname;//对路径进行解码以防中文乱码pathName = decodeURI(pathName);//获取资源文件的绝对路径var filePath = path.resolve(__dirname+pathName);console.log("请求图片资源绝对路径:",filePath);//获取文件的扩展名var extName = path.extname(pathName);//设置内容类型var contentType = mime[extName] || "text/plain";//根据读取文件状态来决定如何读取静态文件fs.stat(filePath,function(err,stats){//读取图片文件错误处理if(err){res.writeHead(404,{"content-type":"text/html"});res.end("<h1>404 没有找到 </h1>");}//文件存在if(!err && stats.isFile()){readFile(filePath,contentType);}//图片文件流式读取function readFile(filePath,contentType){//设置http消息头res.writeHead(200,{"content-type":contentType,"content-encoding":"gzip"});//创建流对象读取文件var stream = fs.createReadStream(filePath);stream.on("error",function(){res.writeHead(500,{"content-type":contentType});res.end("<h1>500 服务器错误</h1>");});//链式管道操作将文件内容流到客户端stream.pipe(zlib.createGzip()).pipe(res);}//如果路径是目录if(!err && stats.isDirectory()){var html = "<head><meta charset = 'utf-8'/></head><body><ul>";//获取当前目录名curDir = path.basename(path.relative(__dirname,filePath));fs.readdir(filePath,(err,files)=>{if(err){console.log("读取路径失败!");}else{for(var file of files){var curPath = path.join(curDir,file);html += "<li><a href = '${curPath}'>${file}</a></li>";}html += "</ul></body>";res.writeHead(200,{"content-type":"text/html"});res.end(html);}});}});});//指定服务器监听的端口
var port = 8000;
server.listen(port,function(){console.log("图片服务器正在运行在端口:${port}");console.log('访问地址:http://localhost:${port}');
});
在该脚本文件目录存放供访问浏览的图片文件
点击运行
打开浏览器,输入链接地址:http://127.0.0.1:8000/green.jpg
可以成功访问服务器端的图片文件。