簡體   English   中英

使用流創建插件gulp

[英]Create plugin gulp with stream

我創建了用於在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;

你是主意

除了不遵守插件准則,沒有什么可以阻止您這樣做的!

用戶實際上假設插件將流傳輸文件,並且可以將其通過管道傳輸到其他插件。

如果我的代碼正確,則您正在嘗試生成一個包含入站文件的所有哈希散列的文件。 為什么不讓用戶使用此文件並將其通過管道傳輸到其他插件? 您會驚訝於人們的能力。

盡管此問題看起來有點基於意見,但您絕對可以將重點放在如何處理可能不屬於主流文件的文件上。 這樣的問題可以在許多插件中找到。 例如, gulp-uglify作者想知道他們如何添加源映射而不將js和源映射下游混合

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM