Skip to content

Instantly share code, notes, and snippets.

@vanderb
Created February 11, 2019 16:58
Show Gist options
  • Save vanderb/69e34fbd3bea93697badf4aa9360bf33 to your computer and use it in GitHub Desktop.
Save vanderb/69e34fbd3bea93697badf4aa9360bf33 to your computer and use it in GitHub Desktop.
Node Inky
var inky = require('./i.js');
var argv = process.argv.slice(2);
var cheerio = require('cheerio');
var path = require('path');
var through = require('through2');
var vfs = require('vinyl-fs');
var Inky = require('inky/lib/inky');
var fs = require('fs');
var mkdirp = require('mkdirp');
var juice = require('juice');
var inky;
function Inky(opts, cb) {
var stream;
opts = opts || {};
opts.cheerio = Inky.mergeCheerioOpts(opts.cheerio);
if (typeof inky === 'undefined') {
inky = new Inky(opts);
}
// If the user passed in source files, create a stream
if (opts.src) {
stream = vfs
.src(opts.src)
.pipe(transform());
if (opts.dest && typeof cb === 'function') {
stream.on('finish', cb);
}
}
// Otherwise, return the transform function
else {
return transform();
}
// This transform function takes in a Vinyl HTML file, converts the code from Inky to HTML, and returns the modified file.
function transform() {
return through.obj(function(file, enc, callback) {
var convertedHtml = inky.releaseTheKraken(file.contents.toString(), opts.cheerio);
var options = {
preserveMediaQueries: true,
webResources: {
scripts: false,
images: 500
}
};
juice.juiceResources(convertedHtml, options, (err, html) => {
convertedHtml = html;
});
file.contents = new Buffer.from(convertedHtml);
// Write to disk manually if the user specified it
if (opts.dest) {
var outputPath = path.join(opts.dest, path.basename(file.path));
mkdirp(opts.dest, function() {
fs.writeFile(outputPath, convertedHtml, callback);
});
}
else {
callback(null, file);
}
});
}
}
inky({
src: argv[0],
dest: argv[1]
}, () => {
console.log('Done parsing.');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment