/** * Get content based on options * could either be a html string or a local file * @param opts * @returns {{promise: *, tmpfiles: Array}} */ function getContentPromise(opts) { if (!(opts.src || opts.html) || !opts.base) { return Promise.reject(new Error('A valid source and base path are required.')); } // html passed in directly -> create tmp file and set opts.url if (opts.html) { return tmp.fileAsync({dir: opts.base, postfix: '.html'}) .then(getFirst) .then(function (path) { opts.url = path; return fs.writeFileAsync(opts.url, opts.html).then(function () { return opts.html; }); }); } // use src file provided return assertLocal(opts)(opts.src) .then(function (data) { // src can either be absolute or relative to opts.base if (opts.src !== path.resolve(data) && !isExternal(opts.src)) { opts.url = path.join(opts.base, opts.src); } else { opts.url = path.relative(process.cwd(), data); } return fs.readFileAsync(opts.url); }); }
/** * Get vinyl object based on options * could either be a html string or a local file. * If opts.src already is a vinyl object it gets returnd without modifications * @param {object} opts Options passed to critical * @returns {promise} resolves to vinyl object */ function getVinylPromise(opts) { if (!(opts.src || opts.html) || !opts.base) { return Bluebird.reject(new Error('A valid source and base path are required.')); } if (isVinyl(opts.src)) { return new Bluebird(resolve => { resolve(opts.src); }); } const file = new File({ base: opts.base }); if (opts.src && isExternal(opts.src)) { file.remotePath = opts.src; } else if (opts.src) { file.path = opts.src; } if (opts.html) { const folder = generateSourcePath(opts); debug('hacky source path folder', folder); // Html passed in directly -> create tmp file return tmp.fileAsync({dir: opts.base, postfix: '.html'}) .then(getFirst) .then(filepath => { file.path = filepath; file.path = path.join(folder, path.basename(filepath)); file.base = folder; file.contents = Buffer.from(opts.html); gc.addFile(filepath); return fs.writeFileAsync(filepath, file.contents).then(() => { return file; }); }); } // Use src file provided, fetch content and return vinyl return assertLocal(opts)(opts.src) .then(data => { // Src can either be absolute or relative to opts.base if (opts.src !== path.resolve(data) && !isExternal(opts.src)) { file.path = path.join(opts.base, opts.src); } else { file.path = path.relative(process.cwd(), data); } return fs.readFileAsync(file.path).then(contents => { file.contents = contents; return file; }); }); }
return function (resp) { var contentType = resp.headers['content-type']; return tmp.fileAsync(_.assign(opts, {postfix: '.' + mime.extension(contentType)})) .then(getFirst) .then(function (path) { gc.addFile(path); return fs.writeFileAsync(path, resp.body).then(function () { return path; }); }); };