From 254a77b8309134401a1df768934a37d6da86a85e Mon Sep 17 00:00:00 2001 From: FleyX <2728474645@qq.com> Date: Tue, 20 Jun 2017 10:21:26 +0800 Subject: [PATCH] Add files via upload --- index.js | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++++ package.json | 15 +++++++++++++ test.js | 2 ++ 3 files changed, 79 insertions(+) create mode 100644 index.js create mode 100644 package.json create mode 100644 test.js diff --git a/index.js b/index.js new file mode 100644 index 0000000..eb206b1 --- /dev/null +++ b/index.js @@ -0,0 +1,62 @@ +const + http=require('http'), + fs=require('fs'), + path=require('path'), + mime=require('mime'), + chatServer=require('./lib/chat_server'); + +var cache={};//缓存静态文件内容 +//发送错误响应 +function send404(response){ + response.writeHead(404,{'Content-Type':'text/plain'}); + response.write('Error 4.4:文件未找到。'); + response.end(); +} +//发送文件内容 +function sendFile(response,filePath,fileContents){ + response.writeHead( + 200, + {"content-Type":mime.lookup(path.basename(filePath))} + ); + response.end(fileContents); +} +//查找文件 +function serveStatic(response,cache,absPath){ + if(cache[absPath]){ + sendFile(response,absPath,cache[absPath]); + }else{ + fs.exists(absPath,function(exists){ + if(exists){ + fs.readFile(absPath,function(err,data){ + if(err){ + send404(response); + }else{ + cache[absPath]=data; + sendFile(response,absPath,data); + } + }); + }else{ + send404(response); + } + }); + } +} + + +//入口 +var server=http.createServer(function(request,response){ + var filePath=false; + console.log(`new request for ${request.url}`); + if(request.url==='/'){ + filePath='public/index.html'; + }else{ + filePath='public'+request.url; + } + + var absPath='./'+filePath; + serveStatic(response,cache,absPath); +}); +server.listen(3000,function(){ + console.log("the server is listening on prot 3000."); +}); +chatServer.listen(server); //websocket服务也绑定到该端口上 \ No newline at end of file diff --git a/package.json b/package.json new file mode 100644 index 0000000..16594cb --- /dev/null +++ b/package.json @@ -0,0 +1,15 @@ +{ + "name": "chat_room", + "version": "1.0.0", + "description": "this is a room where you can chat with your friends", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "author": "sfs", + "license": "ISC", + "dependencies": { + "socket.io":"2.0.3", + "mime":"1.3.6" + } +} diff --git a/test.js b/test.js new file mode 100644 index 0000000..7201630 --- /dev/null +++ b/test.js @@ -0,0 +1,2 @@ +var map=new Map(); +console.log(map.get('sdf')); \ No newline at end of file