Created
April 21, 2016 08:32
-
-
Save branneman/3ff765379c83325f14b178cbf037fd47 to your computer and use it in GitHub Desktop.
Streaming task-runner (how gulp works, simplified)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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