Node.js学习(7)- HTTP协议模块http,url,path,构建HTTP服务器,文件服务器

1.http模块(构建HTTP服务器)

HTTP协议如果是重新开发几乎是不可能的,需要处理tcp协议,解析HTTP等等。这些工作node.js中的http模块以及完成了封装,我们编写程序只需要使用就可以了。

request对象封装了HTTP请求,我们调用request对象的属性和方法就可以拿到所有HTTP请求的信息;

response对象封装了HTTP响应,我们操作response对象的方法,就可以把HTTP响应返回给浏览器。

"sue strict";

//导入http
var http = require("http");
//创建http server,并传入回调函数
var server = http.createServer(function (request, response) {
//    回调函数接收request和response对象
//    获得http请求的method和url
    console.log(request.method + ":" + request.url);
//    将http响应200写入response, 同时设置Content-Type:text/html;
    response.writeHead(200, {"Content-Type":"text/html"});
//    将http响应的html内容写入到response;
    response.end("<h1>Hello world!</h1>");
});

//让服务监听8080端口;
server.listen(8080);
console.log("server is running an http://127.0.0.1:8080");

运行查看效果:

2.url模块

url模块可以解析URL地址。

"use strict";
//引入url模块,url模块是解析URL的。
var url = require("url");
console.log(url.parse("httpL//user:[email protected]:8080/path/to/file?query=string#hash"));

3.path模块

path模块可以操作系统目录。

//引入path模块,path模块是处理操作系统相关的文件路径
var path = require("path");
var workDir = path.resolve(".");
var filePath = path.join(workDir, "pub", "index.html");
console.log(filePath);

4.Node.js构建文件服务器


"use strict";

var fs = require("fs");
var http = require("http");
var path = require("path");
var url = require("url");

//获取当前工作目录
var root = path.resolve(process.argv[2] || ".");
console.log("Static root dir:" + root);

//创建服务器
var server = http.createServer(function (request,response) {
    //文件相对路径 例如 /index.html
    var pathname = url.parse(request.url).pathname;
    console.log(pathname);
    //文件绝对路径 例如 F:/test/nodejs/index.html
    var filepath = path.join(root,pathname);
    console.log(filepath);
    fs.stat(filepath,function (err,stat) {
        if (!err && stat.isFile()){
            console.log("200" + request.url);
            response.writeHead(200);
            fs.createReadStream(filepath).pipe(response);
        }else {
            //返回的错误页面
            console.log("404" + request.url);
            response.writeHead(404);
            response.end("404 not found!");
        }
    })
});

server.listen(8080);
console.log("server is running at http://127.0.0.1:8080");

访问的文件不存在

访问的文件存在(index.html自己创建一个,想偷懒的可以留言找我要)

猜你喜欢

转载自blog.csdn.net/sunhuansheng/article/details/82189902