nodejs文件服务器

2021-04-19 13:26

阅读:474

标签:txt   one   decode   mamicode   服务器   stream   url   pip   read   

本文尝试使用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浏览器:输入http://127.0.0.1:8001/demo/Simple3DEditor/index.html
技术图片
仅供参考!

nodejs文件服务器

标签:txt   one   decode   mamicode   服务器   stream   url   pip   read   

原文地址:https://www.cnblogs.com/MakeView660/p/12268429.html


评论


亲,登录后才可以留言!