当前位置:首页 > Web开发 > 正文

本文尝试使用nodejs搭建一个文件服务器

2024-03-31 Web开发

本文测验考试使用nodejs搭建一个文件处事器。
首先在官方下载node环境并安置:https://nodejs.org/en/download/
安置后node被插手到系统环境变量中。
>node --version
>v12.14.1

1 const http = require("http"); 2 const Path = require("path"); 3 const fs = require("fs"); 4 5 var server = http.createServer(function(req, res) { 6 let currUrl = decodeURIComponent(req.url); 7 const fileName = Path.resolve(__dirname, "../" + currUrl); 8 const extName = Path.extname(fileName).substr(1); 9 10 if (fs.existsSync(fileName)) { //判断本地文件是否存在 11 var mineTypeMap = { 12 html: ‘text/html;charset=utf-8‘, 13 htm: ‘text/html;charset=utf-8‘, 14 xml: "text/xml;charset=utf-8", 15 png: "image/png", 16 jpg: "image/jpeg", 17 jpeg: "image/jpeg", 18 gif: "image/gif", 19 css: "text/css;charset=utf-8", 20 txt: "text/plain;charset=utf-8", 21 mp3: "audio/mpeg", 22 mp4: "video/mp4", 23 ico: "image/x-icon", 24 tif: "image/tiff", 25 svg: "image/svg+xml", 26 zip: "application/zip", 27 ttf: "font/ttf", 28 woff: "font/woff", 29 woff2: "font/woff2", 30 } 31 if (mineTypeMap[extName]) { 32 res.setHeader(‘Content-Type‘, mineTypeMap[extName]); 33 } 34 var stream = fs.createReadStream(fileName); 35 stream.pipe(res); 36 } 37 }) 38 server.listen(8001, function(){ 39 console.log("http server is running on port 8001!"); 40 });

文件目录:

技术图片

运行处事:node index.js

打开chrome浏览器:输入:8001/demo/Simple3DEditor/index.html

技术图片


仅供参考!

nodejs文件处事器

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/30445.html