使用nodejs搭建简单的静态服务器

2019-04-05  本文已影响0人  饥人谷_阿银

前提是已经安装好了nodejs,gitbash等工具,未装的自行前往官方下载安装

step1

获取http模块,创建服务器,监听8080端口

var http = require('http')
var server = http.createServer(function(request, response){
  response.end()
})
server.listen(8080)

step2

上一步相当于已经创建了个服务器,但是请求处理函数未做任何处理,什么请求也处理不了,因此,需要添加一些简单的处理

var http = require('http')
var server = http.createServer(function(request, response){
  response.setHeader('Content-Type','text/html;charset=utf-8')
  //response.write('<head><meta charset="gbk" /></head>')
  response.write('<h1>你好</h1>')
  response.end()
})
server.listen(8080)

这样打开http://localhost:8080/就能看见你好两个字啦。整个过程相当于客户用浏览器访问了http://localhost:8080/,服务器接受到了请求,执行请求处理函数。对response中放入了一些数据并且返回给浏览器。

image

上述有几个注意点:

step3

step2已经能实现服务器返回数据啦!!!但是你是不是有这样的疑惑,我要展示一个写好的html怎么办呢?总不能这样一条一条response.write的写吧。可以利用到nodejs的读写模块(fs),读取相应的html,css,js等文件返回。同时加入了path和url模块。
首先需要找到html,css,js等文件的绝对路径!!!
文件目录结构如下图所示:

image
var http = require('http')
var fs = require('fs')
var url = require('url')
var path = require('path')
var server = http.createServer(function(request, response){
    //获取输入的url解析后的对象
    var pathObj = url.parse(request.url, true);
    //static文件夹的绝对路径
    var staticPath = path.resolve(__dirname, 'static')
    //获取资源文件绝对路径
    var filePath = path.join(staticPath, pathObj.pathname)
    if(filePath.indexOf('favicon.ico') === -1){//屏蔽浏览器默认对favicon.ico的请求
        //同步读取file
        var fileContent = fs.readFileSync(filePath,'binary')
        response.write(fileContent, 'binary')
    }
    response.end()
})
server.listen(8080)
console.log('visit http://localhost:8080')

浏览器中输入的url为http://localhost:8080/login.html?aa=001&bb=002
//request.url经过url.parse(request.url, true)解析后的对象
Url {
  protocol: null,
  slashes: null,
  auth: null,
  host: null,
  port: null,
  hostname: null,
  hash: null,
  search: '?aa=001&bb=002',
  query: { aa: '001', bb: '002' },
  pathname: '/login.html',
  path: '/login.html?aa=001&bb=002',
  href: '/login.html?aa=001&bb=002' }

step4

step3已经可以展示相应的html,css,js等文件了。但是多试验几次会发现几个新的问题!!!
①同步读文件,如果文件很大的话,对后面代码的执行很不友好
②如果url中输入的文件不存在的话,读取不到文件,导致服务器挂掉
因此,用异步读取文件的方式来完善。

var http = require('http')
var fs = require('fs')
var url = require('url')
var path = require('path')
var server = http.createServer(function(request, response){
    //获取输入的url解析后的对象
    var pathObj = url.parse(request.url, true);
    //static文件夹的绝对路径
    var staticPath = path.resolve(__dirname, 'static')
    //获取资源文件绝对路径
    var filePath = path.join(staticPath, pathObj.pathname)
    //异步读取file
    fs.readFile(filePath, 'binary', function(err, fileContent){
        if(err){
            console.log('404')
            response.writeHead(404, 'not found')
            response.end('<h1>404 Not Found</h1>')
        }else{
            console.log('ok')
            response.write(fileContent, 'binary')
            response.end()
        }
    })
})
server.listen(8080)
console.log('visit http://localhost:8080')
上一篇 下一篇

猜你喜欢

热点阅读