用Nodejs写一个 HTTP/206 下载
时间: 2024-05-08 13:21:52 浏览: 165
下面是一个简单的 Node.js HTTP/206 下载示例:
```javascript
const http = require('http')
const fs = require('fs')
const file = 'path/to/file'
const stat = fs.statSync(file)
const fileSize = stat.size
const server = http.createServer((req, res) => {
const range = req.headers.range
if (range) {
const parts = range.replace(/bytes=/, '').split('-')
const start = parseInt(parts[0], 10)
const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1
const chunksize = (end - start) + 1
const fileStream = fs.createReadStream(file, { start, end })
const headers = {
'Content-Range': `bytes ${start}-${end}/${fileSize}`,
'Accept-Ranges': 'bytes',
'Content-Length': chunksize,
'Content-Type': 'video/mp4'
}
res.writeHead(206, headers)
fileStream.pipe(res)
} else {
const headers = {
'Content-Length': fileSize,
'Content-Type': 'video/mp4'
}
res.writeHead(200, headers)
fs.createReadStream(file).pipe(res)
}
})
server.listen(3000, () => {
console.log('Server started on port 3000')
})
```
这个示例代码会启动一个 HTTP 服务器,监听 3000 端口,当客户端请求视频资源时,会返回对应的 HTTP/206 响应,支持断点续传。
阅读全文