使用 Stream 处理
使用 Stream 处理
极力推荐让你所写的插件支持 stream。这里有一些关于让插件支持 stream 的一些有用信息。
请确保使用处理错误的最佳实践,并且加入一行代码,使得 gulp 能在转换内容的期间在捕获到第一个错误时候正确报出错误。
编写插件 > 编写以 stream 为基础的插件
使用 stream 处理
让我们来实现一个用于在文件头部插入一些文本的插件,这个插件支持 file.contents 所有可能的形式。
var through = require('through2');
var gutil = require('gulp-util');
var PluginError = gutil.PluginError;
// 常量
const PLUGIN_NAME = 'gulp-prefixer';
function prefixStream(prefixText) {
var stream = through();
stream.write(prefixText);
return stream;
}
// 插件级别函数 (处理文件)
function gulpPrefixer(prefixText) {
if (!prefixText) {
throw new PluginError(PLUGIN_NAME, 'Missing prefix text!');
}
prefixText = new Buffer(prefixText); // 预先分配
// 创建一个让每个文件通过的 stream 通道
var stream = through.obj(function(file, enc, cb) {
if (file.isBuffer()) {
this.emit('error', new PluginError(PLUGIN_NAME, 'Buffers not supported!'));
return cb();
}
if (file.isStream()) {
// 定义转换内容的 streamer
var streamer = prefixStream(prefixText);
// 从 streamer 中捕获错误,并发出一个 gulp的错误
streamer.on('error', this.emit.bind(this, 'error'));
// 开始转换
file.contents = file.contents.pipe(streamer);
}
// 确保文件进去下一个插件
this.push(file);
// 告诉 stream 转换工作完成
cb();
});
// 返回文件 stream
return stream;
}
// 暴露(export)插件的主函数
module.exports = gulpPrefixer;
上面的插件可以像这样使用:
var gulp = require('gulp');
var gulpPrefixer = require('gulp-prefixer');
gulp.src('files/**/*.js', { buffer: false })
.pipe(gulpPrefixer('prepended string'))
.pipe(gulp.dest('modified-files'));
一些使用 stream 的插件
有疑问、勘误、请您在下方留言,感谢您的支持 ღ( ´・ᴗ・` )!
感谢您阅读,这篇文章归 极客点子版权所有.
如果转载,请注明出处: 极客点子版权所有(/page/661.html)
本网站使用 创作共用 归属 - 非商业用途 - 共享4.0国际许可协议的相同方式 许可.
如果转载,请注明出处: 极客点子版权所有(/page/661.html)

本网站使用 创作共用 归属 - 非商业用途 - 共享4.0国际许可协议的相同方式 许可.
- You Don't Know JS: Async & Performance Appendix B: Advanced Async Patterns
- 6.You Don't Know JS: ES6 & Beyond Chapter 5: Collections
- You Don't Know JS: ES6 & Beyond Chapter 6: API Additions
- 2.You Don't Know JS: ES6 & Beyond Chapter 1: ES? Now & Future
- You Don't Know JS: ES6 & Beyond Chapter 8: Beyond ES6
博文分类
- nodejs
- express
- thinkjs
- go
- beego
- javascript
- css3
- react native
- python3
- react
- 翻译
- 手册
- 树莓
- Error修复
- 五味
- IoT
- 技巧
- swift
- Android
- C++
- ruby
- perl
- linux
- mysql
- pgSQL
- Redis
- webpack
- C
- Object-C
- SOA
- browserify
- unix
- NDK
- C#
- Docker
- java
- PHP
- gulp
- Sass
- Data mining
- Architecture
- Laravel
- TCP/IP
- AI
- Unix Socket
- Lua
- League of Legends
- tensorflow
- minecraft
- flutter
- dart2
- mongodb
- Julia
- UML
- typescript
- rust
- nginx
- 极客时间
- 架构与道
- 算法
- RHCA