Node.js/stream/拷贝:修订间差异
来自康健生活
无编辑摘要 |
无编辑摘要 |
||
| 第74行: | 第74行: | ||
return Promise.resolve(stream); | return Promise.resolve(stream); | ||
}</syntaxhighlight> | }</syntaxhighlight> | ||
=== 克隆 === | |||
<syntaxhighlight lang="javascript"> | |||
let Readable = require('stream').Readable; | |||
let fs = require('fs'); | |||
let path = require('path'); | |||
class NewReadable extends Readable{ | |||
constructor(originReadable){ | |||
super(); | |||
this.originReadable = originReadable; | |||
this.start(); | |||
} | |||
start() { | |||
this.originReadable.on('data',(chunck)=>{ | |||
this.push(chunck); | |||
}); | |||
this.originReadable.on('end',()=>{ | |||
this.push(null); | |||
}); | |||
this.originReadable.on('error',(e)=>{ | |||
this.push(e); | |||
}); | |||
} | |||
// 作为Readable的实现类,必须实现_read函数,否则会throw Error | |||
_read(){ | |||
} | |||
} | |||
app.use(async (ctx,next) => { | |||
let cloneReq = new NewReadable(ctx.req); | |||
let cloneReq2 = new NewReadable(ctx.req); | |||
// 此时,ctx.req已被消费完(没有内容),所有的数据都完全在克隆出的两个流上 | |||
// 消费cloneReq,获取认证数据 | |||
let body = JSON.parse(decodeURIComponent(await parse({req: cloneReq}))); | |||
// 将克隆出的cloneReq2重新设置原型链,继承ctx.req原有属性 | |||
cloneReq2.__proto__ = ctx.req; | |||
// 此后重新给ctx.req复制,留给后续过滤器消费 | |||
ctx.req = cloneReq2; | |||
if(body.name != 'admin'){ | |||
return ctx.body = 'permission denied!' | |||
} | |||
await next(); | |||
})</syntaxhighlight> | |||
=== Transform === | |||
<syntaxhighlight lang="javascript"> | |||
// 认证 | |||
app.use(async (ctx,next) => { | |||
// let cloneReq = new NewReadable(ctx.req); | |||
// let cloneReq2 = new NewReadable(ctx.req); | |||
let cloneReq = new Transform({ | |||
highWaterMark: 10*1024*1024, | |||
transform: (chunk,encode,next)=>{ | |||
next(null,chunk); | |||
} | |||
}); | |||
let cloneReq2 = new Transform({ | |||
highWaterMark: 10*1024*1024, | |||
transform: (chunk,encode,next)=>{ | |||
next(null,chunk); | |||
} | |||
}); | |||
ctx.req.pipe(cloneReq) | |||
ctx.req.pipe(cloneReq2) | |||
// 此时,ctx.req已被消费完(没有内容),所有的数据都完全在克隆出的两个流上 | |||
// 消费cloneReq,获取认证数据 | |||
let body = JSON.parse(decodeURIComponent(await parse({req: cloneReq}))); | |||
// 将克隆出的cloneReq2重新设置原型链,继承ctx.req原有属性 | |||
cloneReq2.__proto__ = ctx.req; | |||
// 此后重新给ctx.req复制,留给后续过滤器消费 | |||
ctx.req = cloneReq2; | |||
if(body.name != 'admin'){ | |||
return ctx.body = 'permission denied!' | |||
} | |||
await next(); | |||
})</syntaxhighlight> | |||