Skip to content

Commit

Permalink
fix: Buffer.from(<string>) requires nodejs 4.5+ (#2)
Browse files Browse the repository at this point in the history
Add version detection and use deprecated `new Buffer(<string>)`, if the
new Buffer API isn't supported by runtime.

See nodejs/node#7562.
  • Loading branch information
macedigital committed Mar 13, 2017
1 parent c67e109 commit 32604ba
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
16 changes: 13 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,11 @@ var crypto = require('crypto');
var path = require('path');
var through = require('through2');
var cheerio = require('cheerio');
var semver = require('semver');
var PluginError = require('gulp-util').PluginError;

var NODE_VERSION_WITH_NEW_BUFFER_API = '4.5.0';
var useDeprecatedBufferApi = semver.lt(process.version, NODE_VERSION_WITH_NEW_BUFFER_API);
var PLUGIN_NAME = 'gulp-sri-hash';
var DEFAULT_ALGO = 'sha384';
var DEFAULT_SELECTOR = 'link[href][rel=stylesheet]:not([integrity]), script[src]:not([integrity])';
Expand All @@ -16,6 +19,14 @@ var cache;
module.exports = gulpSriHashPlugin;
module.exports.PLUGIN_NAME = PLUGIN_NAME;

function makeBufferFromString(string) {
if (useDeprecatedBufferApi) {
return new Buffer(string);
}

return Buffer.from(string);
}

function normalizePath(node, config) {
var src = node.name == 'script' ? node.attribs.src : node.attribs.href;

Expand Down Expand Up @@ -51,9 +62,8 @@ function resolveAbsolutePath(file, localPath) {

function calculateSri(fullPath, algorithm) {
var file = fs.readFileSync(fullPath);
var digest = crypto.createHash(algorithm).update(file).digest();

return Buffer.from(digest).toString('base64');
return crypto.createHash(algorithm).update(file).digest('base64');
}

function getFileHash(fullPath, algorithm) {
Expand All @@ -73,7 +83,7 @@ function updateDOM(file, config) {

if ($candidates.length > 0) {
$candidates.each(addIntegrityAttribute);
file.contents = Buffer.from($.html());
file.contents = makeBufferFromString($.html());
}

return file;
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
"cheerio": "^0.22.0",
"gulp": "^3.9.1",
"gulp-util": "^3.0.7",
"semver": "^5.3.0",
"through2": "^2.0.1"
},
"engines": {
Expand Down

0 comments on commit 32604ba

Please sign in to comment.