面试题答案
一键面试- 引入必要模块:
在Node.js中,首先需要引入
http
模块来创建HTTP服务器,引入fs
模块来读取文件,引入zlib
模块来进行数据压缩。const http = require('http'); const fs = require('fs'); const zlib = require('zlib');
- 创建HTTP服务器并设置响应:
读取文件内容,通过
zlib
模块的createGzip
方法创建一个压缩流,将文件内容管道到压缩流,再将压缩流管道到HTTP响应。const server = http.createServer((req, res) => { const filePath = 'largeTextFile.txt';// 假设的大文本文件路径 const readStream = fs.createReadStream(filePath); const gzip = zlib.createGzip(); res.writeHead(200, { 'Content-Type': 'text/plain', 'Content-Encoding': 'gzip' }); readStream.pipe(gzip).pipe(res); readStream.on('error', (err) => { res.writeHead(500, { 'Content-Type': 'text/plain' }); res.end('Error reading file'); }); gzip.on('error', (err) => { res.writeHead(500, { 'Content-Type': 'text/plain' }); res.end('Error compressing data'); }); }); const port = 3000; server.listen(port, () => { console.log(`Server running on port ${port}`); });
上述代码中:
- 首先引入了
http
、fs
和zlib
模块。 - 创建HTTP服务器,当有请求到来时,尝试读取指定的大文本文件。
- 通过
zlib.createGzip()
创建一个Gzip压缩流。 - 设置HTTP响应头,告知客户端数据是经过Gzip压缩的。
- 使用
pipe
方法将文件读取流连接到压缩流,再将压缩流连接到HTTP响应流,实现数据的高效传输。 - 同时处理文件读取和数据压缩过程中可能出现的错误,并返回相应的错误信息给客户端。