Node.js学习之路day3

1.只会helloworld的服务器

http模块提供了request对象和response对象。
request对象封装了http请求,通过调用request对象的属性和方法,可以拿到http请求相关的信息。
response对象封装了http响应,操作response对象的方法可以返回http响应。
一个简单的helloworld栗子

let http=require('http')
//创建服务器对象
let server=http.createServer(function(request,response){
    console.log('first node server')
    //http响应200
    response.writeHead(200,{'content-Type':'text/html'})
    //响应内容为helloworld
    response.write('<p>helloworld</p>')
    response.end()
})
server.listen(8080)

终端使用node test.js命令运行,打开浏览器localhost:8080

image.png

2.可返回文档的服务器

可以解析请求中得url,从url分析到对应的文件名,将本地的对应文件返回即可
这里需要引入url模块,path模块,以及前两篇博客里的fs模块
代码及注释如下

let http=require('http')
let fs=require('fs')
let url=require('url')
let path=require('path')
let server=http.createServer(function(request,response){
   let p=url.parse(request.url).pathname   //获得url中的文件路径
   let root = path.resolve(process.argv[2] || '.');//获得当前目录的路径
   let currentPath=root+p  //拼接路径
   fs.stat(currentPath,function(err,stat){
     if(!err&&stat.isFile()){   //没有出错并且文件存在
       response.writeHead(200)
       fs.createReadStream(currentPath).pipe(response)  //以管道流形式传输给response
     }else{
       response.writeHead(404)
       response.end('<p>404</p>')
     }
   })
})
server.listen(8080)

读取txt

image.png

读取html

image.png

404

image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容