2018年9月16日(周天)

through2模块

through2模块

一句话介绍

through2在流管道中可以对可读流进行修改,主要依赖readable-stream模块

优点

和"data"事件比较
// 使用data事件,也可以实现对可读流的修改
fs.createReadStream(path).on('data',data=>{
	data[0]=97;
	fs.createWriteStream(path).write(data);
});
data事件缺点:
	ReadStream如果比WriteStream速度快的话,会造成数据丢失
	可以使用readable.resume()、readable.pause()解决,但是代码较长

和 pipe()方法比较

// 使用pipe方法不用担心数据丢失的问题
fs.createReadStream(path).pipe(fs.createWriteStream(path));
pipe方法缺点
	不能修改数据

使用

through2([ options, ] [ transformFunction ] [, flushFunction ])
option: 参数
	

const fs = require('fs');
const through2 = require('through2');

fs.createReadStream('./demo.js')
.pipe(through2(function (chunk, enc, callback) {
  // chunk 为数据流
  // enc 数据格式 buffer
  chunk[ 0 ] = 97;
  this.push(chunk);
  callback();
}))
.pipe(fs.createWriteStream('./demo.txt'));

使用官方API实现

// transform模块
module.exports = (fn) => {
  const transform = new Transform({
    transform: fn,
  });
  return transform;
};
// 使用
const transform = require('./transform');
const fs = require('fs');

fs.createReadStream('./app.js').pipe(transform(function (chunk, encoding, callback) {
// 此处使用箭头函数需要注意,this不是Transform实例
  chunk[ 0 ] = 97;
  this.push(chunk);
  callback();
})).pipe(fs.createWriteStream('./app.txt'));

也可以使用ES6继承

class Th extends Transform {
  constructor(options) {
    super(options);
  }

  _transform(chunk, encoding, callback) {
    // 在内部可以进行任何操作
    callback();
  }
}
// 因为Transform是可读流及可写流,如果想连续调用pipe()方法,需要将Transform的可写流数据传入可读流中:
	调用Readable.push(chunk)传入可读流中
	
	_transform(chunk, encoding, callback) {
		// 在内部可以进行任何操作
		this.push(chunk);
		callback();
	}
	
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值