在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML/ node zlib使用gzip報(bào)Error: write after end

node zlib使用gzip報(bào)Error: write after end

http請(qǐng)求靜態(tài)文件返回使用gzip壓縮時(shí)候報(bào)錯(cuò),不開啟gzip使用注釋部分則正常

關(guān)鍵代碼片段:

const gzip = require('zlib').createGzip();

res.statusCode = 200;
res.setHeader('Content-Type', type);
res.setHeader('Content-Encoding', 'gzip');

// fs.readFile(pathname, (err, data) => {
//   res.end(data);
// })

fs.createReadStream(pathname).pipe(gzip).pipe(res); //關(guān)鍵語句

報(bào)錯(cuò):

Error: write after end
    at writeAfterEnd (_stream_writable.js:195:12)
    at Gzip.Writable.write (_stream_writable.js:242:5)
    at ReadStream.ondata (_stream_readable.js:555:20)
    at emitOne (events.js:96:13)
    at ReadStream.emit (events.js:188:7)
    at readableAddChunk (_stream_readable.js:176:18)
    at ReadStream.Readable.push (_stream_readable.js:134:10)
    at onread (fs.js:2026:12)
    at FSReqWrap.wrapper [as oncomplete] (fs.js:683:17)

較小的html文件能正確返回,比較大css和js卻返回不了,請(qǐng)問下我這是哪里寫錯(cuò)了或是少了什么嗎?

回答
編輯回答
尐潴豬

你應(yīng)該在每次接收到請(qǐng)求的時(shí)候, 新創(chuàng)建一個(gè) gzip 對(duì)象, 而不是在一開始的時(shí)候就創(chuàng)建。

const gzip = require('zlib').createGzip;

//...

fs.createReadStream(pathname).pipe(gzip()).pipe(res);

另外, 推薦使用現(xiàn)成的庫(kù), 比如compression。

2017年12月25日 12:37
編輯回答
陌南塵
const zlib = require('zlib');
...
fs.createReadStream(pathname).pipe(zlib.createGzip()).pipe(res);
2017年8月9日 05:33