-
Notifications
You must be signed in to change notification settings - Fork 0
Step1
wulin edited this page Jul 17, 2016
·
1 revision
此步骤我们主要讲解通过nodejs怎样将请求转发到后面真正提供服务的server
这次我们要用到stream和request模块
Stream在nodejs中是EventEmitter的实现,并且有多种实现形式,例如:
- http responses request
- fs read write streams
- zlib streams
- tcp sockets
- child process stdout and stderr
其中ReadableStream有一个pipe方法
readable.pipe(destination[, options])
//=>destination <stream.Writable> 第一个参数是一个可写的流下面一个例子是将file.txtgzip压缩至file.txt.gz
const r = fs.createReadStream('file.txt');
const z = zlib.createGzip();
const w = fs.createWriteStream('file.txt.gz');
r.pipe(z).pipe(w);在request 模块中, 因为返回了一个可读可写的流,所以可以使用pipe方法进行数据流传输到另一个请求中。它可以把method/headers/entity-body data一起传输给下一个请求;
req.pipe(request(targetUrl)).on('error', function(err) {
// 处理目标服务器错误
res.status(404).send('Not found:' + req.originalUrl);
return;
}).on('response', function(response) {
// redis缓存处理
var bodyChunks = [];
response.on('data', function(chunk) {
bodyChunks.push(chunk);
}).on('end', function() {
var body = Buffer.concat(bodyChunks);
//*****do somethings
});
}).pipe(res);
req是用户提交过来的请求,是一个可写的流
request(targetUrl) 用request创建一个对project4或者project5接口的请求,返回一个可读可写的流
req.pipe(request(targetUrl))
相当于将请求过来的参数原样提交到project4或project5,并且将返回的可读流重定向至用户的返回response(res)