如: 我要展示本地 http://localhost:8888/test.html
搭建本地的一个站点n

那我肯定得找到 test.html 文件了

第一步、找到目标存放目录 

当前我是放在桌面的 ,无所谓

搭建本地的一个站点

copy   目录: C:\Users\pc\Desktop\project

第二步、肯定得依赖环境 搭建服务了 最简便的方式 当然是用 node.js
 

废话不多说上代码吧

// server.js
var http = require('http')
var fs = require('fs') //引入文件读取模块

var documentRoot = 'C:/Users/pc/Desktop/project'
//需要访问的文件的存放目录

var server = http
  .createServer(function(req, res) {
    var url = req.url
    //客户端输入的url,例如如果输入localhost:8888/index.html
    //那么这里的url == /index.html

    var file = documentRoot + url
    console.log(url)
    //E:/PhpProject/html5/websocket/www/index.html

    fs.readFile(file, function(err, data) {
      /*
        一参为文件路径
        二参为回调函数
            回调函数的一参为读取错误返回的信息,返回空就没有错误
            二参为读取成功返回的文本内容
    */
      if (err) {
        res.writeHeader(404, {
          'content-type': 'text/html;charset="utf-8"'
        })
        res.write('<h1>404错误</h1><p>你要找的页面不存在</p>')
        res.end()
      } else {
        res.writeHeader(200, {
          'content-type': 'text/html;charset="utf-8"'
        })
        res.write(data) //将index.html显示在客户端
        res.end()
      }
    })
  })
  .listen(8888)

console.log('服务器开启成功')

 

服务代码 ,目录资源读取   刚才第一步取出的 文件 存入  完美
 

第三部、在node 环境下启动 server.js  我同样放桌面了

搭建本地的一个站点

当然了  在浏览器输入 localhost:8888  测试环境是否搭建完成
读取资源  localhost:8888/test.html

 

相关文章: