http://nodejs.cn/api/http.html node html模块api
http://nodejs.cn/api/fs.html node fs模块api
目录/
index.js
home.html
about.html
notfound.html
pubilc/ // 静态资源文件路径
img/
logo.jpg
<!DOCTYPE HTML>
<html lang="zh-cn">
<head>
<meta http-equiv="Content-Type" content="text/html;charset:utf-8;" />
<title>homepage</title>
<head>
<body>
<img href="./img/logo.jpg" alt="logo"/>
</body>
</html>
<!DOCTYPE HTML>
<html lang="zh-cn">
<head>
<meta http-equiv="Content-Type" content="text/html;charset:utf-8;" />
<title>about</title>
<head>
<body></body>
</html>
<!DOCTYPE HTML>
<html lang="zh-cn">
<head>
<meta http-equiv="Content-Type" content="text/html;charset:utf-8;" />
<title>not found</title>
<head>
<body>404</body>
</html>
<!DOCTYPE HTML>
<html lang="zh-cn">
<head>
<meta http-equiv="Content-Type" content="text/html;charset:utf-8;" />
<title>about</title>
<head>
<body></body>
</html>
// index.js
/** 第一版代码
var http = require('http');
http.createServer(function(req, res){
res.writeHead(200, {'Content-Type':'text/plain'});
res.end('hello world!');
}).listen(3000);
console.log('Server started on localhost:3000; press Ctrl+c to terminate...');
*/
/** 第二版代码
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...');
*/
var http = require('http'),
fs = require('fs');
function serverStaticFile(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 '':
serverStaticFile(res, '/home.html', 'text/html');
break;
case '/about':
serverStaticFile(res, '/about.html', 'text/html');
break;
case '/img/logo.jpg':
serverStaticFile(res, '/img/logo.jpg', 'image/jpeg');
break;
default:
serverStaticFile(res, '/notfound.html', 'text/html', 404);
break;
}
}).listen(3000);
console.log('Server started on localhost:3000; press Ctrl+c to terminate...');