Last active
April 29, 2017 01:52
-
-
Save wastemobile/656b9976b37aaf50930919b5cb1600e5 to your computer and use it in GitHub Desktop.
一個檔案理解 Node for Web
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var http = require('http'), | |
fs = require('fs'); | |
function serveStaticFile(res, path, contentType, responseCode) { | |
if(!responseCode) responseCode = 200; | |
fs.readFile(__dirname + path, function(err, data){ | |
if(err) { | |
res.writeHead(500, {'Content-Type': 'text/plain'}); | |
res.end('500 - Internal Error'); | |
} else { | |
res.writeHead(responseCode, {'Content-Type': contentType}); | |
res.end(data); | |
} | |
}); | |
} | |
http.createServer(function(req, res){ | |
var path = req.url.replace(/\/?(?:\?.*)?$/, '').toLowerCase(); | |
switch(path) { | |
case '': | |
serveStaticFile(res, '/public/home.html', 'text/html'); | |
break; | |
case '/about': | |
serveStaticFile(res, '/public/about.html', 'text/html'); | |
break; | |
case '/img/logo.jpg': | |
serveStaticFile(res, '/public/img/logo.jpg', 'image/jpeg'); | |
break; | |
default: | |
serveStaticFile(res, '/public/404.html', 'text/html', 404); | |
break; | |
} | |
}).listen(3000); | |
console.log('伺服器開在3000埠,按Ctrl-C終止運行⋯⋯'); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var http = require('http'); | |
http.createServer(function(req, res){ | |
var path = req.url.replace(/\/?(?:\?.*)?$/, '').toLowerCase(); | |
switch(path) { | |
case '': | |
res.writeHead(200, {'Content-Type': 'text/plain'}); | |
res.end('Homepage'); | |
break; | |
case '/about': | |
res.writeHead(200, {'Content-Type': 'text/plain'}); | |
res.end('About'); | |
break; | |
default: | |
res.writeHead(404, {'Content-Type': 'text/plain'}); | |
res.end('Not Found'); | |
break | |
} | |
}).listen(3000); | |
console.log('Server started on localhost 3000; press Ctrl-C to terminate...'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment