gulp-srcToVariable.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. var through = require('through2');
  2. var gutil = require('gulp-util');
  3. var PluginError = gutil.PluginError;
  4. var path = require('path');
  5. var File = gutil.File;
  6. // Consts
  7. const PLUGIN_NAME = 'gulp-srcToVariable';
  8. var srcToVariable = function srcToVariable(varName, asMap, namingCallback) {
  9. var content;
  10. var firstFile;
  11. namingCallback = namingCallback || function(filename) { return filename; };
  12. function bufferContents(file, enc, cb) {
  13. // ignore empty files
  14. if (file.isNull()) {
  15. cb();
  16. return;
  17. }
  18. // no stream support, only files.
  19. if (file.isStream()) {
  20. this.emit('error', new PluginError('gulp-concat', 'Streaming not supported'));
  21. cb();
  22. return;
  23. }
  24. // set first file if not already set
  25. if (!firstFile) {
  26. firstFile = file;
  27. }
  28. // construct concat instance
  29. if (!content) {
  30. content = asMap ? {} : "";
  31. }
  32. // add file to concat instance
  33. if(asMap) {
  34. var name = namingCallback(file.relative);
  35. content[name] = file.contents.toString();
  36. } else {
  37. content += file.contents.toString();
  38. }
  39. cb();
  40. }
  41. function endStream(cb) {
  42. if (!firstFile || !content) {
  43. cb();
  44. return;
  45. }
  46. var joinedPath = path.join(firstFile.base, varName);
  47. var joinedFile = new File({
  48. cwd: firstFile.cwd,
  49. base: firstFile.base,
  50. path: joinedPath,
  51. contents: new Buffer(varName + '=' + JSON.stringify(content) + ';')
  52. });
  53. this.push(joinedFile);
  54. cb();
  55. }
  56. return through.obj(bufferContents, endStream);
  57. }
  58. module.exports = srcToVariable;