博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Nodejs实现简易HTTP服务器
阅读量:4110 次
发布时间:2019-05-25

本文共 4092 字,大约阅读时间需要 13 分钟。

很早以前没事干搞的,来体验一下Nodejs的回调地狱

const http = require('http');const path = require('path');const fs = require('fs');const url = require('url');const formidable = require('formidable');const sd = require("silly-datetime");const server = http.createServer((request,response)=>{
const pathname = url.parse(request.url).pathname; const query = url.parse(request.url,true).query; //这里加true 就和querystring.parse的效果一样了 //search 是get请求包含?的信息 比如会返回 ?a=b //query 是 get请求的信息,和search的区别是 search 是包含了?和& 但是上面的代码我加了true 等于他会解析成类似dictionary的内容 //path url 除了域名端口所有信息 //href 目前没发现和path有什么区别 //console.log(pathname,query) //下面详细区分mime var resType = "application/octet-stream;"; //默认的 const extension = path.extname(pathname); //获取扩展文件名 // 就写这么多 有兴趣可以从任意一个web容器mime里拷出来 const mimeType = {
".html":"text/html;charset=utf-8;", ".htm":"text/html;charset=utf-8;", ".jpg":"image/jpeg;", ".jpeg":"image/jpeg;", ".png":"image/png;", ".gif":"image/gif;", ".ico":"image/vnd.microsoft.icon;", ".txt":"text/plain;charset=utf-8;", ".json":"application/json;", ".mp4":"video/mp4;", ".ogg":"video/ogg;", ".js":"application/x-javascript;charset=utf-8;", ".mjs":"application/x-javascript;charset=utf-8;", ".css":"text/css;charset=utf-8;" }; if (Object.keys(mimeType).indexOf(extension)>-1){
resType = mimeType[extension]; } console.log(pathname+" "+request.url+" "+request.method); if (pathname=='/'){
fs.readFile("./result.html",function(err,data){
if (err){
response.writeHead(404,{
"Content-type": "text/html;charset=utf-8;"}); response.end('

404 Not Found

'); return false; } response.writeHead(200, {
'content-type': 'text/html;charset=utf-8;'}); response.end(data); }) }else if(pathname=='/favicon.ico'){
response.writeHead(200,{
"Content-type": resType}); fs.readFile("./favicon.ico",(err,data)=>{
if (err){
response.end(); return false; } response.write(data); response.end(); }); }else if(pathname == "/upload" && request.method == "POST"){
var form = new formidable.IncomingForm(); //设置文件上传存放地址 form.uploadDir = "./uploads"; //执行里面的回调函数的时候,表单已经全部接收完毕了。 form.parse(request, function(err, fields, files) {
//console.log(fields) var fileTime = sd.format(new Date(), 'YYYYMMDDHHmmss'); var ran = parseInt(Math.random() * 89999 + 10000); var extname = path.extname(files.upload.name); //执行改名 var oldpath = __dirname + "/" + files.upload.path; //新的路径由三个部分组成:时间戳、随机数、拓展名 var newpath = __dirname + "/uploads/" + fileTime + ran + extname; //改名 fs.rename(oldpath,newpath,function(err){
if(err){
throw Error("改名失败"); } response.writeHead(200, {
'content-type': 'text/plain'}); response.end("成功"); }); }); }else{
// 扩展名限制 if (extension && Object.keys(mimeType).indexOf(extension)<0){
response.writeHead(403,{
"Content-type": "text/html;charset=utf-8;"}); response.end(`

禁止访问 ${
extension} 扩展名文件

`); return false; } fs.stat(path.join(__dirname,pathname),(err,stats)=>{
if (err){
response.writeHead(404,{
"Content-type": "text/html;charset=utf-8;"}); response.end('

404 Not Found

'); return false; } fs.readFile(path.join(__dirname,pathname),(err,data)=>{
if (err){
response.writeHead(403,{
"Content-type": "text/html;charset=utf-8;"}); response.end('

403 Forbidden

'); return false; } /* 这样是优先判断文件是否存在,存在且访问不存在扩展名才会触发,可能会造成人家用来判断文件是否存在的特征 if (Object.keys(mimeType).indexOf(extension)<0){ response.writeHead(403,{"Content-type": "text/html;charset=utf-8;"}); response.end(`

禁止访问 ${extension} 扩展名文件

`); return false; } */ response.writeHead(200,{
"Content-type": resType}); response.write(data); response.end(); }); }); }});server.listen(2080,(error)=>{
if (error) throw error; console.log('成功启动web服务,端口:2080');});

转载地址:http://htlsi.baihongyu.com/

你可能感兴趣的文章
OpenFeign学习(六):OpenFign进行表单提交参数或传输文件
查看>>
OpenFeign学习(七):Spring Cloud OpenFeign的使用
查看>>
Ribbon 学习(二):Spring Cloud Ribbon 加载配置原理
查看>>
Ribbon 学习(三):RestTemplate 请求负载流程解析
查看>>
深入理解HashMap
查看>>
XML生成(一):DOM生成XML
查看>>
XML生成(三):JDOM生成
查看>>
Ubuntu Could not open lock file /var/lib/dpkg/lock - open (13:Permission denied)
查看>>
collect2: ld returned 1 exit status
查看>>
C#入门
查看>>
查找最大值最小值
查看>>
杨辉三角
查看>>
C#中ColorDialog需点两次确定才会退出的问题
查看>>
16、Memento 备忘录模式
查看>>
Java基础篇(一)
查看>>
数据库
查看>>
mysql update与group by
查看>>
nginx反代 499 502 bad gateway 和timeout
查看>>
linux虚拟机安装tar.gz版jdk步骤详解
查看>>
python猜拳游戏
查看>>