Nodejs 这样写不对么?不能成功
Nodejs 这样写不对么?不能成功
if(decodeURI(url.parse(req.url).pathname)=="/方正卡通简体.ttf"){ fs.readFile("./方正卡通简体.ttf",Buffer,function(err,data){ zlib.gzip(data, function(err,buffer){ if(!err){ res.writeHead(200,{‘Content-Type’:“application/x-font-ttf”,“Content-Length”:data.length,“Accept-Encoding”:‘gzip’}); res.end(buffer,“binary”); } else{ console.log(err); } }) }) }
不能用 TAT
根据你提供的代码片段,看起来你在尝试从文件系统读取一个字体文件(.ttf
文件),然后将其压缩并发送给客户端。然而,这段代码存在一些问题,比如错误处理不充分、响应头中的内容长度计算有误等。以下是一个改进后的版本,并附带解释:
改进后的代码
const http = require('http');
const url = require('url');
const fs = require('fs');
const zlib = require('zlib');
const server = http.createServer((req, res) => {
const pathname = decodeURI(url.parse(req.url).pathname);
if (pathname === "/方正卡通简体.ttf") {
fs.readFile('./方正卡通简体.ttf', (err, data) => {
if (err) {
console.error("Error reading file:", err);
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Internal Server Error');
return;
}
zlib.gzip(data, (err, buffer) => {
if (err) {
console.error("Error compressing file:", err);
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Internal Server Error');
return;
}
res.writeHead(200, {
'Content-Type': 'application/x-font-ttf',
'Content-Length': buffer.length,
'Content-Encoding': 'gzip'
});
res.end(buffer, 'binary');
});
});
} else {
// 如果请求的不是字体文件,则返回404
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
}
});
server.listen(3000, () => {
console.log('Server is running on port 3000');
});
解释
- 错误处理:在读取文件和压缩数据的过程中添加了错误处理逻辑,确保在发生错误时能够正确响应。
- 内容长度:使用压缩后的数据长度 (
buffer.length
) 来设置Content-Length
头,而不是原始数据的长度。 - Content-Encoding:添加了
Content-Encoding: gzip
头,以指示响应体已被压缩。 - 文件路径:假设字体文件位于服务器的根目录下。如果文件位置不同,请相应调整路径。
通过这些修改,你的代码应该可以正常工作,能够读取字体文件、对其进行压缩,并将压缩后的文件发送给客户端。
没有用框架?
head里用标准的下载头部。不要用TTF头。
根据你的描述,这段代码的主要目的是读取一个字体文件并将其压缩后返回给客户端。从你提供的代码来看,有几个问题需要修正:
Buffer
在 Node.js 中应该作为require('buffer').Buffer
引入,但在大多数情况下可以直接使用Buffer
。- 在
fs.readFile
的回调函数中,第二个参数已经是缓冲区(Buffer),无需再次转换为 Buffer。 res.writeHead
中的 MIME 类型应是"application/octet-stream"
而不是"application/x-font-ttf"
,尽管后者也是有效的 MIME 类型,但前者更常见于字体文件。Content-Length
应该是压缩后的数据长度,而不是原始数据长度。
修正后的代码如下:
const url = require('url');
const fs = require('fs');
const zlib = require('zlib');
if (decodeURI(url.parse(req.url).pathname) === "/方正卡通简体.ttf") {
fs.readFile("./方正卡通简体.ttf", (err, data) => {
if (err) {
console.log(err);
return;
}
zlib.gzip(data, (err, buffer) => {
if (!err) {
res.writeHead(200, {
'Content-Type': 'application/octet-stream',
'Content-Length': buffer.length,
'Accept-Encoding': 'gzip'
});
res.end(buffer, 'binary');
} else {
console.log(err);
}
});
});
}
此段代码将正确处理字体文件的读取、压缩,并将其返回给客户端。如果过程中发生错误,也会输出错误信息。