【问题标题】:Create plugin gulp with stream使用流创建插件 gulp
【发布时间】:2014-03-14 11:09:15
【问题描述】:

我创建了用于在 json 文件中发送 json 数据的插件。

但我不明白为什么要在管道中发送我的对象 json,而不是直接在我的插件中写入文件。

我想用这个语法使用我的插件:

gulp.task('js-hash', function()
{
    // Get all js in redis
    gulp.src('./build/js/**/*.js')
        .pipe(getHashFile('/build/js/'))
       .pipe(gulp.dest('./build/js/hash.json'));
});

不是这样的:

gulp.task('js-hash', function()
{
    // Get all js in redis
    gulp.src('./build/js/**/*.js')
        .pipe(getHashFile('./build/js/hash.json', '/build/js/'));
});

这是我的插件:

var through = require('through2');
var gutil = require('gulp-util');
var crypto = require('crypto');
var fs = require('fs');
var PluginError = gutil.PluginError;

// Consts
const PLUGIN_NAME = 'get-hash-file';
var json = {};

function getHashFile(filename, basename)
{
    if (!filename) {
        throw PluginError(PLUGIN_NAME, "Missing filename !");
    }

    // Creating a stream through which each file will pass
    var stream = through.obj(function (file, enc, callback) {
        if (file.isNull()) {
            this.push(file); // Do nothing if no contents
          return callback();
        }

        if (file.isBuffer()) {
            var hash = crypto.createHash('sha256').update(String(file.contents)).digest('hex');
            json[file.path.replace(file.cwd+basename, '')] = hash;

            return callback();
        }

        if (file.isStream()) {
            this.emit('error', new PluginError(PLUGIN_NAME, 'Stream not supported!'));
            return callback();
        }
    }).on('finish', function () {
        fs.writeFile(filename, JSON.stringify(json), function(err) {
            if (err) {
                throw err;
            }
        });
    });


    // returning the file stream
    return stream;
}


// Exporting the plugin main function
module.exports = getHashFile;

你的想法

【问题讨论】:

    标签: javascript json plugins gulp


    【解决方案1】:

    没有什么能阻止你这样做......除了not respecting plugins guidelines

    用户实际上假设一个插件会流式传输文件,并且他们可以将它们通过管道传输到其他插件。

    如果我的代码正确,那么您正在尝试生成一个包含入站文件的所有 sha 哈希值的文件。为什么不让用户获取此文件并将其通过管道传输到其他插件?你会惊讶于人们能做什么。

    虽然这个问题看起来有点基于意见,但您绝对可以将重点放在如何处理可能不属于文件主流的文件上。类似的问题可以在很多插件中找到;例如,gulp-uglify authors are wondering how they can add source-maps without mixing js and source map downstream

    【讨论】:

      猜你喜欢
      • 2023-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-11
      • 2020-12-21
      • 1970-01-01
      相关资源
      最近更新 更多