Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Node-Stream入门示例(草稿) #70

Open
onvno opened this issue Jul 27, 2016 · 0 comments
Open

Node-Stream入门示例(草稿) #70

onvno opened this issue Jul 27, 2016 · 0 comments

Comments

@onvno
Copy link
Contributor

onvno commented Jul 27, 2016

实现读取文件,之前的readfile可实现,如下:

var server = http.createServer(function(req, res) {
    fs.readFile(__dirname + '/cont/vue.html', function(err, data) {
        if(err) {
            res.statusCode = 500;
            res.end(String(err));
        } else {
            res.end(data);
        }
    });
});

上方法存在以下问题:

文件内容都直接缓存在内存中,影响并发速度

优化方法:

var server = http.createServer(function(req, res) {
    var stream = fs.createReadStream(__dirname + '/cont/vue.html');
    stream.pipe(res);
})

server.listen(8000);
console.log('正在打开http://localhost:8000/')

使用stream实现优化,且代码简洁.

进一步,实现gzip

var http = require('http');
var fs = require('fs');
var zlib = require('zlib');
var server = http.createServer(function(req, res) {
    res.writeHead(200, {'content-encoding': 'gzip'});
    var stream = fs.createReadStream(__dirname + '/cont/vue.html');
    stream.pipe(zlib.createGzip()).pipe(res);
});

server.listen(8000);
console.log('正在打开http://localhost:8000/')

完整代码及其他相关node代码,见https://github.com/onvno/node-module

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant