分享一个用Node.js写一个简单的静态资源服务器,可以了解一些和后端配合的请求头
什么是静态资源服务器
一般客户端发送请求到web服务器,web服务器从内存中取到相应的文件,返回给客户端,客户端解析并渲染显示出来,一般不和数据库打交道,实际应用中像一些提供CDN服务的服务商
代码
#!/usr/bin/env node
// 当系统看到这一行的时候,首先会到env设置里查找node的安装路径,
// 再调用对应路径下的解释器程序完成操作
const fs = require('fs') // fileSystem
const url = require('url')
const http = require('http')
const path = require('path')
const zlib = require('zlib')
const wwwroot = '/work/nodejs' // 网站根目录路径
const ContentType = {
'.html': 'text/html',
'.png': 'image/png',
'.jpg': 'image/jpeg',
}
// ContentType 可以扩展
const server = http.createServer((req, res) => {
// 例子:访问路径为http://127.0.0.1:3737/index.html
// pathname为/index.html
const { pathname } = url.parse(req.url)
console.log('pathname',pathname) // /index.html
const filePath = path.join(wwwroot, pathname)
const ext = path.extname(pathname)
console.log('filePath',filePath) // \work\nodejs\index.html
console.log('ext',ext) // 后缀 .html
// 设置基本请求头
res.statusCode = 200
res.setHeader('Content-Type', ContentType[ext])
res.setHeader('Cache-Control', 'max-age=3600')
res.setHeader('Content-Encoding', 'gzip')
// 创建可读流
const stream = fs.createReadStream(filePath, {
// 打开文件用于读取。如果文件不存在,则会发生异常
flags: 'r'
})
stream.on('error', () => {
res.writeHead(404)
res.end()
})
// 创建转化流
let compress = zlib.createGzip();
// 输出文件流
stream.pipe(compress).pipe(res)
})
server.on('error', error => console.log(error))
server.listen(3737, '127.0.0.1')
代码都在注释里,代码示例只是一个demo,用于学习,不能用于生产,还有一些资源缓存的逻辑没有展示,像请求头设置 Last-Modified 和 304 状态码等。
Tips:
根目录下没有favicon.ico文件会报错
执行node index.js (代码在index.js里)
本地访问 http://127.0.0.1:3737/index.html index.html就被渲染到页面了
// ContentType 可以扩展 此处可以通过增加对象扩展其他文件类型的访问,例如,访问json文件,增加以下代码
'.json': 'application/json'