做者:QILIN
github: https://github.com/1999hk
项目地址(欢迎star): https://github.com/1999hk/nod...
了解前端(客户端)与后端(服务器)javascript
文件目录css
server-static文件夹html
css文件夹前端
img文件夹java
node内置模块node
自定义模块git
/** * 静态资源服务器 * nodeJS 的 commonJS (同步) */ // 用于建立服务器 const http = require('http') // 用于读取文件 const fs = require('fs') // 用于url地址格式化 const url = require('url') // 用于格式化文件地址 const path = require('path') // 自定义模块(用于告诉浏览器返回回去的是什么类型的文件,方便浏览器识别解析) const mime = require('./mime') // 建立一个服务器 const app = http.createServer((request, response) => { // 静态资源服务器:根据不一样的请求,返回不一样的内容 let { pathname } = url.parse(request.url, true) // 获取真实路径 把相对路径装换为决路径 // 把/img/minge.js -> C:\Users\hk\Desktop\nodejs\static_server\img // __dirname: 当前文件所在目录 let realPath = path.join(__dirname, pathname) // 利用path.extname来获取文件的后缀名 let extname = path.extname(pathname).slice(1) // 要显示index.html // 1.经过fs模块读取index.html内容 // 2.经过res.write把内容响应到客户端 // fs.readFile('../index.html', (error, content) => {}) fs.readFile(realPath, (error, content) => { // error错误信息:默认为unll // 告诉浏览器 内容类型是什么 (Content-type) response.writeHead(200, { 'content-type': mime[extname] + ';charset=utf8' }) // 响应内容(能够是屡次) response.write(content) // 结束响应 response.end() }) }) // 监听端口 app.listen(2020, () => { console.log('server is runing on port 1909') })
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <!-- 请求 --> <link rel="stylesheet" href="../css/page.css"> <title>静态资源服务器</title> </head> <body> <h2>minge</h2> <!-- 请求 --> <img src="../img/minge.jpg" alt=""> </body> </html>
module.exports = { "css": "text/css", "gif": "image/gif", "html": "text/html", "ico": "image/x-icon", "jpeg": "image/jpeg", "jpg": "image/jpeg", "js": "text/javascript", "json": "application/json", "pdf": "application/pdf", "png": "image/png", "svg": "image/svg+xml", "swf": "application/x-shockwave-flash", "tiff": "image/tiff", "txt": "text/plain", "wav": "audio/x-wav", "wma": "audio/x-ms-wma", "wmv": "video/x-ms-wmv", "xml": "text/xml" }
前端学习资料大全: https://github.com/1999hk