练习
在浏览器输入http://localhost:8080/时,会返回404,原因是程序识别出HTTP请求的不是文件,而是目录。请修改file_server.js,如果遇到请求的路径是目录,则自动在目录下依次搜索index.html、default.html,如果找到了,就返回HTML文件的内容。
代码
文件夹目录
'use strict'
//实现一个文件服务器
//文件服务器(File server),又称档案伺服器,是指在计算机网络环境中,所有用户都可访问的文件存储设备,
//是一种专供其他电脑检索文件和存储的特殊电脑。
var fs = require('fs'),
url = require('url'),
path = require('path'),
http = require('http');
//从命令行参数获取root目录,默认是当前目录;
var root = path.resolve(process.argv[2] || '.');
console.log('Static root dir:'+root);
//创建服务器:
var server = http.createServer(function (request,response) {
//获得URL的path,类似'/css/bootstrap.css':
var pathname = url.parse(request.url).pathname;
//获得对应的本地文件路径,类似'/srv/www/css/bootstrap.css';
var filepath = path.join(root,pathname);
//获取文件状态:
fs.stat(filepath,function (err,stats){
if(!err && stats.isFile()){
//没有出错并且文件存在:
console.log('200'+request.url);
//发送200响应
response.writeHead(200);
//将文件流导向response:
fs.createReadStream(filepath).pipe(response);
}else if(!err && stats.isDirectory()) {
var indexpath = path.join(filepath,'index.html');
fs.exists(indexpath,function (exists) {
if (exists){
console.log('200'+request.url);
response.writeHead(200);
fs.createReadStream(indexpath).pipe(response);
}else {
var defualtpath = path.join(filepath,'default.html');
fs.exists(defualtpath,function (exists) {
if (exists){
console.log('200'+request.url);
response.writeHead(200);
fs.createReadStream(indexpath).pipe(response);
}else {
console.log('404'+request.url);
response.writeHead(404);
response.end('404 Not Found');
}
})
}
})
}else {
//出错了或者文件不存在
console.log('404'+request.url);
//发送404响应
response.writeHead(404);
response.end('404 Not Found');
}
});
});
server.listen(8080);
console.log('Server is running at http://127.0.0.1:8080/');
运行命令行语句
node path_server.js /test/path