Node.js/stream/拷贝:修订间差异

来自康健生活
Kangkk​(留言 | 贡献)
创建页面,内容为“<syntaxhighlight lang="javascript"> const fs = require('fs') rs = fs.createReadStream('./sss.txt',{ highWaterMark:4 }) ws = fs.createWriteStream('./jj.txt',{…”
 
Kangkk​(留言 | 贡献)
无编辑摘要
 
(未显示同一用户的1个中间版本)
第26行: 第26行:
ws.on('drain',function(){
ws.on('drain',function(){
     rs.resume()//写完继续读,重新触发data
     rs.resume()//写完继续读,重新触发data
})</syntaxhighlight>
=== PassThrough ===
<syntaxhighlight lang="javascript">
const spawn = require('child_process').spawn;
const PassThrough = require('stream').PassThrough;
const a = spawn('echo', ['hi user']);
const b = new PassThrough();
const c = new PassThrough();
a.stdout.pipe(b);
a.stdout.pipe(c);
let count = 0;
b.on('data', function (chunk) {
  count += chunk.length;
});
b.on('end', function () {
  console.log(count);
  c.pipe(process.stdout);
});</syntaxhighlight>
注意,仅当生成的命令输出的字节数未填充反压缓冲区时,此技术才有效。以不同的速率读取流,则会产生问题。
=== concat-stream ===
要缓冲结果,您可以使用concat-stream
<syntaxhighlight lang="javascript">
const Promise = require('bluebird');
const concat = require('concat-stream');
const getBuffer = function(stream){
    return new Promise(function(resolve, reject){
        var gotBuffer = function(buffer){
            resolve(buffer);
        }
        var concatStream = concat(gotBuffer);
        stream.on('error', reject);
        stream.pipe(concatStream);
    });
}</syntaxhighlight>
要从缓冲区创建流,可以使用:
<syntaxhighlight lang="javascript">
const { Readable } = require('stream');
const getBufferStream = function(buffer){
    const stream = new Readable();
    stream.push(buffer);
    stream.push(null);
    return Promise.resolve(stream);
}</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>
})</syntaxhighlight>

2020年5月16日 (六) 10:17的最新版本

const fs = require('fs')
rs = fs.createReadStream('./sss.txt',{
    highWaterMark:4
})
ws = fs.createWriteStream('./jj.txt',{
    highWaterMark:1
})
rs.pipe(ws)

通过读流和写流实现拷贝

const fs = require('fs')
rs = fs.createReadStream('./sss.txt',{
    highWaterMark:4//读的多,写的少
})
ws = fs.createWriteStream('./jj.txt',{
    highWaterMark:1
})
rs.on('data',function (chunk) {
    let flag=ws.write(chunk)
    if(!flag){
        //说明满了
        rs.pause()//暂停读取
    }
})
ws.on('drain',function(){
    rs.resume()//写完继续读,重新触发data
})

PassThrough

const spawn = require('child_process').spawn;
const PassThrough = require('stream').PassThrough;

const a = spawn('echo', ['hi user']);
const b = new PassThrough();
const c = new PassThrough();

a.stdout.pipe(b);
a.stdout.pipe(c);

let count = 0;
b.on('data', function (chunk) {
  count += chunk.length;
});
b.on('end', function () {
  console.log(count);
  c.pipe(process.stdout);
});

注意,仅当生成的命令输出的字节数未填充反压缓冲区时,此技术才有效。以不同的速率读取流,则会产生问题。

concat-stream

要缓冲结果,您可以使用concat-stream

const Promise = require('bluebird');
const concat = require('concat-stream');
const getBuffer = function(stream){
    return new Promise(function(resolve, reject){
        var gotBuffer = function(buffer){
            resolve(buffer);
        }
        var concatStream = concat(gotBuffer);
        stream.on('error', reject);
        stream.pipe(concatStream);
    });
}

要从缓冲区创建流,可以使用:

const { Readable } = require('stream');
const getBufferStream = function(buffer){
    const stream = new Readable();
    stream.push(buffer);
    stream.push(null);
    return Promise.resolve(stream);
}

克隆

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();
})

Transform

// 认证
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();
})