如何在express中压缩fs.createReadStream

时间:2017-08-06 07:32:39

标签: node.js express compression

我有这段代码;

const express = require('express')
const compression = require('compression')
const app = express()
const fs = require('fs');
const path = require('path');
const port = process.env.PORT || 3003;

app.use(compression())
app.use('/public', express.static('public'));

app.get('/', (req, res) => {
    fs.createReadStream(__dirname + '/public/src/index/index.html').pipe(res);
});

app.listen(port, () => {
    console.log(`Portfolio listening on port ${port}`)
})

在chrome dev工具中,app.js中请求的index.html文件被gzip压缩,但第一个文件(上面代码中引用的index.html)不是。

如何在流式传输之前压缩index.html文件?

1 个答案:

答案 0 :(得分:1)

如何使用zlib模块:

fs.createReadStream(__dirname + '/public/src/index/index.html')
  .pipe(zlib.createGzip())
  .pipe(res);