Skip to content

Instantly share code, notes, and snippets.

@branneman
Created April 21, 2016 08:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save branneman/3ff765379c83325f14b178cbf037fd47 to your computer and use it in GitHub Desktop.
Save branneman/3ff765379c83325f14b178cbf037fd47 to your computer and use it in GitHub Desktop.
Streaming task-runner (how gulp works, simplified)
'use strict';
const fs = require('fs');
const glob = require('glob').sync;
const mkdirp = require('mkdirp').sync;
const sass = require('node-sass');
const path = require('path');
const streams = require('stream');
const runner = {};
/**
* Glob from source
*/
runner.src = function(globStr) {
const fileQueue = glob(globStr);
const rs = streams.Readable({ objectMode: true });
rs._read = function() {
const file = fileQueue.shift();
if (file) {
this.push({
filename: file,
contents: fs.readFileSync(file, { encoding: 'utf8' })
});
}
};
return rs;
};
/**
* Save to destination
*/
runner.dest = function(basePath) {
const ws = streams.Writable({ objectMode: true });
ws._write = file => {
mkdirp(path.dirname(basePath + file.filename));
fs.writeFileSync(basePath + file.filename, file.contents);
};
return ws;
};
/**
* Example Plugin: Sass
*/
const compileSass = function() {
const ts = streams.Transform({ objectMode: true });
ts._transform = function(file) {
sass.render({ data: file.contents }, (err, result) => {
file.filename = file.filename.replace(/\.scss$/, '.css');
file.contents = result.css.toString();
this.push(file);
});
};
return ts;
};
/**
* Usage
*/
runner.src('scss/*.scss')
.pipe(compileSass())
.pipe(runner.dest('css/'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment