Skip to content

Instantly share code, notes, and snippets.

@CITguy
Last active January 13, 2023 19:23
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save CITguy/079c631ac5f181939e08 to your computer and use it in GitHub Desktop.
Save CITguy/079c631ac5f181939e08 to your computer and use it in GitHub Desktop.
Basic pattern for creating a custom Transform stream for use with gulp tasks.
var gulp = require('gulp');
var myTransform = require('./myTransform');
gulp.task('foobar', function (){
return gulp.src("foobar.js")
.pipe(myTransform())
.pipe(gulp.dest('.'));
});
var through = require('through2');
module.exports = function () {
// return a `through2` stream for `pipe()` compatibility at the node level
return through.obj(function (vinylFile, encoding, callback) {
// 1. clone new vinyl file for manipulation
// (See https://github.com/wearefractal/vinyl for vinyl attributes and functions)
var transformedFile = vinylFile.clone();
// 2. set new contents
// * contents can only be a Buffer, Stream, or null
// * This allows us to modify the vinyl file in memory and prevents the need to write back to the file system.
transformedFile.contents = new Buffer("whatever");
// 3. pass along transformed file for use in next `pipe()`
callback(null, transformedFile);
});
}//myTransform()
@Manc
Copy link

Manc commented Jul 5, 2019

Thanks!

@SteinTheRuler
Copy link

just what I needed. I was complicating it with arrays and streams. much cleaner this way

@Keuter
Copy link

Keuter commented Feb 28, 2020

Great! I wrote a little gulp-wrapper for it, see: https://www.npmjs.com/package/gulp-minify-html-literals.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment