Skip to content

Commit 32604ba

Browse files
committed
fix: Buffer.from(<string>) requires nodejs 4.5+ (#2)
Add version detection and use deprecated `new Buffer(<string>)`, if the new Buffer API isn't supported by runtime. See nodejs/node#7562.
1 parent c67e109 commit 32604ba

2 files changed

Lines changed: 14 additions & 3 deletions

File tree

index.js

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,11 @@ var crypto = require('crypto');
55
var path = require('path');
66
var through = require('through2');
77
var cheerio = require('cheerio');
8+
var semver = require('semver');
89
var PluginError = require('gulp-util').PluginError;
910

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

22+
function makeBufferFromString(string) {
23+
if (useDeprecatedBufferApi) {
24+
return new Buffer(string);
25+
}
26+
27+
return Buffer.from(string);
28+
}
29+
1930
function normalizePath(node, config) {
2031
var src = node.name == 'script' ? node.attribs.src : node.attribs.href;
2132

@@ -51,9 +62,8 @@ function resolveAbsolutePath(file, localPath) {
5162

5263
function calculateSri(fullPath, algorithm) {
5364
var file = fs.readFileSync(fullPath);
54-
var digest = crypto.createHash(algorithm).update(file).digest();
5565

56-
return Buffer.from(digest).toString('base64');
66+
return crypto.createHash(algorithm).update(file).digest('base64');
5767
}
5868

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

7484
if ($candidates.length > 0) {
7585
$candidates.each(addIntegrityAttribute);
76-
file.contents = Buffer.from($.html());
86+
file.contents = makeBufferFromString($.html());
7787
}
7888

7989
return file;

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
"cheerio": "^0.22.0",
3030
"gulp": "^3.9.1",
3131
"gulp-util": "^3.0.7",
32+
"semver": "^5.3.0",
3233
"through2": "^2.0.1"
3334
},
3435
"engines": {

0 commit comments

Comments
 (0)