HTTP服务器
http 模块的 request 对象封装了HTTP请求,我们调用request对象的属性和方法就可以拿到所有HTTP请求的信息;
http 模块的 response 对象封装了HTTP响应,我们操作response对象的方法,就可以把HTTP响应返回给浏览器。
Node.js实现一个HTTP服务器程序http.js
'use strict';
var http = require('http');
//创建http server
var server = http.createServer(function(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>nodeJS http module</h1>')
})
//让服务器监听8888端口
server.listen(8888);
执行下列命令行
$ node http.js
GET:/
GET:/favicon.ico
在浏览器输入 localhost:8888
文件服务器
'use strict';
var fs = require('fs');
var url = require('url');//解析URL
var path = require('path');//处理本地目录使用
var http = require('http');
//从命令行参数获取root目录,默认是当前目录
var root = path.resolve(process.argv[2]||'.');
console.log('根目录路径' + root);
//创建服务器
var server = http.createServer(function(request, response){
//获取URL的path
var pathName = url.parse(request.url).pathname;
console.log('pathname:' + pathName);
//获取对应的本地文件路径
var filePath = path.join(root,pathName);
console.log('filePath:' + filePath);
//获取文件的状态
fs.stat(filePath,function(err,stats){
if(!err && stats.isFile()){
console.log('200' + request.url);
//发送200响应
response.writeHead(200,{'Content-Type':'text/html'});
response.end('<h1>200</h1>');
//将文件导向response
fs.createReadStream(filePath).pipe(response);
}else{
//出错了
console.log('404' + request.url);
//发送404响应
response.writeHead(404);
response.end('404 not found');
}
})
});
server.listen(8087);
在浏览器URL里面输入http://localhost:8087/index.html,显示结果如下:
参考文章:
nodejs
liaoxuefeng