001-搭建简单服务器,访问本地静态资源

    技术2022-07-11  141

    node下载地址:http://nodejs.cn/ Node.js是一个事件驱动I/O服务端JavaScript环境,基于Google的V8引擎,V8引擎执行Javascript的速度非常快,性能非常好。 使用nodejs搭建本地服务器,类似于Apache。 操作步骤: 1、在文件夹下创建一个服务文件server.js。 2、进入server.js文件,打开命令面板,运行命令node serve.js。 若服务启动成功,命令面本中会打印日志“服务器开启成功”。 在浏览器中,输入localhost:8888可以成功访问。 3、访问文件可以在地址栏目中加入访问的文件路径 4、关闭服务器:ctrl + c,根据命令板提示操作即可关闭。

    以下是详细代码

    const http = require('http') // 文件阅读器 const fs = require('fs') const url = require('url') const path = require("path") // 一、搭建、开启服务 const server = http.createServer(function(req, res){ // req:接收客户端传来的数据 // res:想服务端发送的数据 // 若要访问其他文件夹下的文件,需要修改root目录 const root = __dirname // const root = "E:\project\nodeServe" // __dirname被执行文件的绝对路径 // parse(url),url的拆解,常见方法还有host、port、pathname、path、query。 let filePath = root + url.parse(req.url).pathname if (path.extname(filePath) == "") { filePath += "/test.html" } // charAt(index)返回指定位置字符 if (filePath.charAt(filePath.length - 1) == '/') { filePath += 'index.html' } fs.exists(filePath, function (exists) { // 查看文件路劲是否存在 // exists(filePath,callBack) if (exists) { const contentTypeObj = { // 根据后缀名设置content-type值 '.html': { "Content-Type": 'text/html;charset="utf-8"' }, '.js': { "Content-Type": "text/javascript" }, '.css': { "Content-Type": "text/css" }, '.gif': { "Content-Type": "image/gif" }, '.png': { "Content-Type": "image/png" }, } const fileExtname = path.extname(filePath) // extname()获取文件的拓展名(后缀名) fs.readFile(filePath, function (err, data) { // readFile // 一参:文件路径 // 二参:回调函数 if (err) { res.writeHead(404, { 'content-type': 'text/html;charset="utf-8"' }) res.write('<div>读取错误</div>') res.end() return } res.writeHead(200, contentTypeObj[path.extname(filePath)]) // writeHead // 第一个参数是http请求码,200为连接成功 // 二参:连接成功后向客户端写入头信息 // 把内容写入document中 res.write(data) // 发送信息 res.end() }) return } res.writeHead(404, { "content-Type": 'text/html;charset="utf-8"' }) res.end("<h1>文件不存在!</h1>") }) }).listen(8888) // listen(要监听的端口) console.log('nodejs服务器已经开启!')
    Processed: 0.013, SQL: 9