Node.Js学习—廖雪峰JavaScript教程之Node.Js章节http练习作业

练习

在浏览器输入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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值