node中http模块

node自带的http模块,连接、解析等基础功能,所以应用程序并不直接和http协议打交道,而是操作http模块提供的request和response对象。

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

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

用node实现的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'});
response. end( '<h1>node server</h1>')
})
server. listen( 8081);
console. log( 'server is running at http://127.0.0.1:8081')

文件服务器:让我们继续扩展一下上面的web程序。我们可以设定一个目录,然后让web程序变成一个文件服务器。要实现这一点,我们只需解析request.url中的路径,然后在本地找到对应的文件,把文件内容发送出去就可以了。

解析url需要用到node提供的url模块,它用起来非常简单,通过parse()将一个字符串解析为url对象。处理本地文件目录,需要用到node提供的path模块,它可以方便的构造目录。使用path模块可以正确的处理操作系统相关的文件路径。在windows下,返回路径类似 C:\Users\Administrator\Desktop\ReadingCompanion,这样我们就先不关心这么拼接路径了

'use strict'
var fs = require( 'fs'),
http = require( 'http'),
url = require( 'url'),
path = require( 'path');
//从命令行参数获取root目录,默认是当前目录
var root = path. resolve( process. argv[ 2] || '.');
console. log( 'Static root dir:'+ root);
//创建服务器
var server = http. createServer( function ( request, response) {
//获取url的path
var pathname = url. parse( request. url). pathname;
//获得对应的本地文件路径
var filepath = path. join( root, pathname);
// 获取文件状态
fs. stat( filepath, function ( err, stats) {
if(! err && stats. isFile()){
//没有出错,并且文件存在
console. log( '200'+ request. url);
response. writeHead( 200);
//将文件流导向response
fs. createReadStream( filepath). pipe( response);
} else{
//出错了或者文件不存在
console. log( '404'+ request. url);
response. end( '404 Not Found')
}
})
})
server. listen( 8082);
console. log( 'File server is running in http://127.0.0.1:8082');

没有必要手动读取文件内容。由于response本身是一个Writeable Stream,直接同pipe()就实现了自动读取文件内容并输出到http响应。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值