UNPKG

fd-gulp-encodingfilter

Version:

filt the assigned encoding file

64 lines (42 loc) 1.5 kB
'use strict'; var through = require('through'); var gutil = require('gulp-util'); var PluginError = gutil.PluginError; var Path = require('path'); var File = gutil.File; var Buffer = require('buffer').Buffer; var jschardet = require('jschardet'); var FLAG = 'STYLE_BUILD_ERR '; module.exports = function (encoding) { var pluginName = 'fd-gulp-encodingfilter'; var errorCache = []; if( typeof encoding !== 'string' || !encoding.trim().length ) { throw new PluginError(pluginName, 'encoding is empty'); } function filter (file) { var self = this; if (file.isNull()) { return; } if (file.isStream()) { return this.emit("error", new PluginError(pluginName, 'Streaming not supported')); } var filePath = file.path; var filebuffer = file.contents; var detectObj = jschardet.detect(filebuffer); var fileEncoding = detectObj.encoding ? detectObj.encoding.toLowerCase() : encoding; var filterEncoding = encoding.toLowerCase(); if( filterEncoding !== fileEncoding ) { errorCache.push('file: ' + filePath + ' encoding: ' + fileEncoding + ' confidence ' + detectObj.confidence); } } function endStream() { if (errorCache.length === 0){ return this.emit('end'); } throw new PluginError(pluginName, FLAG + 'the file encoding should ' + encoding + ' but ' + errorCache.join('\n')) } return through(filter, endStream); };