nodejs文件服务器

此生再无相见时 提交于 2020-02-06 15:22:43

本文尝试使用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

仅供参考!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!