Repository: node-nock/nock
Pull request #1144 (2018-06-07 15:23:51)

Revert "refactor: update Buffer constructors to from and alloc (#1141)"
This reverts commit e933b3a4a5b7ca598d789026978f718b5049fb92.

This restores compatibility with Node<4


Patch:
diff --git a/lib/common.js b/lib/common.js
index b50b5a0..fb03dac 100644
--- a/lib/common.js
+++ b/lib/common.js
@@ -50,7 +50,7 @@ var isBinaryBuffer = function(buffer) {
 
   //  Test if the buffer can be reconstructed verbatim from its utf8 encoding.
   var utfEncodedBuffer = buffer.toString('utf8');
-  var reconstructedBuffer = Buffer.from(utfEncodedBuffer, 'utf8');
+  var reconstructedBuffer = new Buffer(utfEncodedBuffer, 'utf8');
   var compareBuffers = function(lhs, rhs) {
     if(lhs.length !== rhs.length) {
       return false;
@@ -80,7 +80,7 @@ var isBinaryBuffer = function(buffer) {
 var mergeChunks = function(chunks) {
 
   if(_.isEmpty(chunks)) {
-    return Buffer.alloc(0);
+    return new Buffer(0);
   }
 
   //  We assume that all chunks are Buffer objects if the first is buffer object.
diff --git a/lib/interceptor.js b/lib/interceptor.js
index f823eb6..3e333b1 100644
--- a/lib/interceptor.js
+++ b/lib/interceptor.js
@@ -395,7 +395,7 @@ Interceptor.prototype.basicAuth = function basicAuth(options) {
     var username = options['user'];
     var password = options['pass'] || '';
     var name = 'authorization';
-    var value = 'Basic ' + Buffer.from(username + ':' + password).toString('base64');
+    var value = 'Basic ' + new Buffer(username + ':' + password).toString('base64');
     this.interceptorMatchHeaders.push({ name: name, value: value });
     return this;
 };
diff --git a/lib/recorder.js b/lib/recorder.js
index ae84d96..2a48aa8 100644
--- a/lib/recorder.js
+++ b/lib/recorder.js
@@ -56,7 +56,7 @@ var getBodyFromChunks = function(chunks, headers) {
       body: _.map(chunks, function(chunk) {
         if(!Buffer.isBuffer(chunk)) {
           if (typeof chunk === 'string') {
-            chunk = Buffer.from(chunk);
+            chunk = new Buffer(chunk);
           } else {
             throw new Error('content-encoded responses must all be binary buffers');
           }
@@ -330,7 +330,7 @@ function record(rec_options) {
       res.push = function(data) {
         if (data) {
           if (encoding) {
-            data = Buffer.from(data, encoding);
+            data = new Buffer(data, encoding);
           }
           dataChunks.push(data);
         }
@@ -358,7 +358,7 @@ function record(rec_options) {
         if (data) {
           debug(thisRecordingId, 'new', proto, 'body chunk');
           if (! Buffer.isBuffer(data)) {
-            data = Buffer.from(data, encoding);
+            data = new Buffer(data, encoding);
           }
           bodyChunks.push(data);
         }
@@ -373,7 +373,7 @@ function record(rec_options) {
         if (data) {
           debug(thisRecordingId, 'new', proto, 'body chunk');
           if (! Buffer.isBuffer(data)) {
-            data = Buffer.from(data, encoding);
+            data = new Buffer(data, encoding);
           }
           bodyChunks.push(data);
         }
diff --git a/lib/request_overrider.js b/lib/request_overrider.js
index 361e26f..94ac73a 100644
--- a/lib/request_overrider.js
+++ b/lib/request_overrider.js
@@ -111,7 +111,7 @@ function RequestOverrider(req, options, interceptors, remove, cb) {
 
   /// options.auth
   if (options.auth && (! options.headers || ! options.headers.authorization)) {
-    setHeader(req, 'Authorization', 'Basic ' + (Buffer.from(options.auth)).toString('base64'));
+    setHeader(req, 'Authorization', 'Basic ' + (new Buffer(options.auth)).toString('base64'));
   }
 
   if (! req.connection) {
@@ -132,7 +132,7 @@ function RequestOverrider(req, options, interceptors, remove, cb) {
     if (!req.aborted) {
       if (buffer) {
         if (!Buffer.isBuffer(buffer)) {
-          buffer = Buffer.from(buffer, encoding);
+          buffer = new Buffer(buffer, encoding);
         }
         requestBodyBuffers.push(buffer);
       }
@@ -319,13 +319,13 @@ function RequestOverrider(req, options, interceptors, remove, cb) {
             emitError(new Error('Gzip encoding is currently not supported in this version of Node.'));
             return;
           }
-          requestBody = String(zlib.gunzipSync(Buffer.from(requestBody, 'hex')), 'hex')
+          requestBody = String(zlib.gunzipSync(new Buffer(requestBody, 'hex')), 'hex')
         } else if (requestBody && common.contentEncoding(options.headers, 'deflate')) {
           if (typeof zlib.deflateSync !== 'function') {
             emitError(new Error('Deflate encoding is currently not supported in this version of Node.'));
             return;
           }
-          requestBody = String(zlib.inflateSync(Buffer.from(requestBody, 'hex')), 'hex')
+          requestBody = String(zlib.inflateSync(new Buffer(requestBody, 'hex')), 'hex')
         }
 
         requestBody = JSON.parse(requestBody);
@@ -357,7 +357,7 @@ function RequestOverrider(req, options, interceptors, remove, cb) {
         }
 
         responseBuffers = _.map(buffers, function(buffer) {
-          return Buffer.from(buffer, 'hex');
+          return new Buffer(buffer, 'hex');
         });
 
       } else {
@@ -369,7 +369,7 @@ function RequestOverrider(req, options, interceptors, remove, cb) {
         if(isBinaryRequestBodyBuffer && typeof(responseBody) === 'string') {
           //  Try to create the buffer from the interceptor's body response as hex.
           try {
-            responseBody = Buffer.from(responseBody, 'hex');
+            responseBody = new Buffer(responseBody, 'hex');
           } catch(err) {
             debug('exception during Buffer construction from hex data:', responseBody, '-', err);
           }
@@ -377,7 +377,7 @@ function RequestOverrider(req, options, interceptors, remove, cb) {
           // Creating buffers does not necessarily throw errors, check for difference in size
           if (!responseBody || (interceptor.body.length > 0 && responseBody.length === 0)) {
             //  We fallback on constructing buffer from utf8 representation of the body.
-            responseBody = Buffer.from(interceptor.body, 'utf8');
+            responseBody = new Buffer(interceptor.body, 'utf8');
           }
         }
       }
@@ -443,7 +443,7 @@ function RequestOverrider(req, options, interceptors, remove, cb) {
           });
         } else if (responseBody && !Buffer.isBuffer(responseBody)) {
           if (typeof responseBody === 'string') {
-            responseBody = Buffer.from(responseBody);
+            responseBody = new Buffer(responseBody);
           } else {
             responseBody = JSON.stringify(responseBody);
             response.headers['content-type'] = 'application/json';
diff --git a/lib/socket.js b/lib/socket.js
index e9b4e87..f99e5bb 100644
--- a/lib/socket.js
+++ b/lib/socket.js
@@ -57,7 +57,7 @@ Socket.prototype.applyDelay = function applyDelay(delayMs) {
 };
 
 Socket.prototype.getPeerCertificate = function getPeerCertificate() {
-  return Buffer.from((Math.random() * 10000 + Date.now()).toString()).toString('base64');
+  return new Buffer((Math.random() * 10000 + Date.now()).toString()).toString('base64');
 };
 
 Socket.prototype.destroy = function destroy() {


Test patch:
diff --git a/tests/test_common.js b/tests/test_common.js
index 3672198..3361727 100644
--- a/tests/test_common.js
+++ b/tests/test_common.js
@@ -74,10 +74,10 @@ tap.test('isBinaryBuffer works', function(t) {
   t.false(common.isBinaryBuffer(''));
 
   //  Returns true for binary buffers.
-  t.true(common.isBinaryBuffer(Buffer.from('8001', 'hex')));
+  t.true(common.isBinaryBuffer(new Buffer('8001', 'hex')));
 
   //  Returns false for buffers containing strings.
-  t.false(common.isBinaryBuffer(Buffer.from('8001', 'utf8')));
+  t.false(common.isBinaryBuffer(new Buffer('8001', 'utf8')));
 
   t.end();
 
diff --git a/tests/test_intercept.js b/tests/test_intercept.js
index fdc68ef..c716dfc 100644
--- a/tests/test_intercept.js
+++ b/tests/test_intercept.js
@@ -1631,7 +1631,7 @@ test("response pipe", function(t) {
     function Constructor() {
       events.EventEmitter.call(this);
 
-      this.buffer = Buffer.alloc(0);
+      this.buffer = new Buffer(0);
       this.writable = true;
     }
 
@@ -1642,7 +1642,7 @@ test("response pipe", function(t) {
     };
 
     Constructor.prototype.write = function(chunk) {
-      var buf = Buffer.alloc(this.buffer.length + chunk.length);
+      var buf = new Buffer(this.buffer.length + chunk.length);
 
       this.buffer.copy(buf);
       chunk.copy(buf, this.buffer.length);
@@ -1682,7 +1682,7 @@ test("response pipe without implicit end", function(t) {
     function Constructor() {
       events.EventEmitter.call(this);
 
-      this.buffer = Buffer.alloc(0);
+      this.buffer = new Buffer(0);
       this.writable = true;
     }
 
@@ -1693,7 +1693,7 @@ test("response pipe without implicit end", function(t) {
     };
 
     Constructor.prototype.write = function(chunk) {
-      var buf = Buffer.alloc(this.buffer.length + chunk.length);
+      var buf = new Buffer(this.buffer.length + chunk.length);
 
       this.buffer.copy(buf);
       chunk.copy(buf, this.buffer.length);
@@ -3750,7 +3750,7 @@ test('define() works with binary buffers', function(t) {
     t.end();
   });
 
-  req.write(Buffer.from(nockDef.body, 'hex'));
+  req.write(new Buffer(nockDef.body, 'hex'));
   req.end();
 
 });
@@ -3873,7 +3873,7 @@ test('sending binary and receiving JSON should work ', function(t) {
   mikealRequest({
     method: 'POST',
     uri: 'http://example.com/some/path',
-    body: Buffer.from('ffd8ffe000104a46494600010101006000600000ff', 'hex'),
+    body: new Buffer('ffd8ffe000104a46494600010101006000600000ff', 'hex'),
     headers: { 'Accept': 'application/json', 'Content-Length': 23861 }
   }, function(err, res, body) {
       scope.done();
@@ -3896,7 +3896,7 @@ test('sending binary and receiving JSON should work ', function(t) {
 
 test('fix #146 - resume() is automatically invoked when the response is drained', function(t) {
   var replyLength = 1024 * 1024;
-  var replyBuffer = Buffer.from((new Array(replyLength + 1)).join("."));
+  var replyBuffer = new Buffer((new Array(replyLength + 1)).join("."));
   t.equal(replyBuffer.length, replyLength);
 
   nock("http://www.abc.com")
@@ -4434,7 +4434,7 @@ test("match basic authentication header", function(t) {
   var username = 'testuser'
     , password = 'testpassword'
     , authString = username + ":" + password
-    , encrypted = (Buffer.from(authString)).toString( 'base64' );
+    , encrypted = (new Buffer(authString)).toString( 'base64' );
 
   var scope = nock('http://www.headdy.com')
      .get('/')
diff --git a/tests/test_isomorphic_fetch.js b/tests/test_isomorphic_fetch.js
index 12d956b..6879aa8 100644
--- a/tests/test_isomorphic_fetch.js
+++ b/tests/test_isomorphic_fetch.js
@@ -61,7 +61,7 @@ test("basicAuth match works", function (t) {
 
   return fetch('http://isomorphicfetchland.com/path2', {
     headers: {
-      'Authorization': 'Basic ' + Buffer.from('username:password').toString('base64'),
+      'Authorization': 'Basic ' + new Buffer('username:password').toString('base64'),
     }
   }).
     then(function (res) {
@@ -78,7 +78,7 @@ test("basicAuth match works", function (t) {
 });
 
 test("matchHeader works", function (t) {
-  var authorizationHeader = 'Basic ' + Buffer.from('username:password').toString('base64');
+  var authorizationHeader = 'Basic ' + new Buffer('username:password').toString('base64');
 
   var scope = nock('http://isomorphicfetchland.com').
     get('/path2').
diff --git a/tests/test_recorder.js b/tests/test_recorder.js
index 2487c8a..1160b0f 100644
--- a/tests/test_recorder.js
+++ b/tests/test_recorder.js
@@ -898,7 +898,7 @@ test("respects http.request() consumers", function(t) {
                   , path:'/' }
     ;
     var req = http.request(options, function (res) {
-      var buffer = Buffer.from('');
+      var buffer = new Buffer('');
 
       setTimeout(function () {
         res
diff --git a/tests/test_s3.js b/tests/test_s3.js
index efa0812..26faf6e 100644
--- a/tests/test_s3.js
+++ b/tests/test_s3.js
@@ -25,7 +25,7 @@ test('works with s3, body < 1024 ^ 2', function (t) {
 
   bucket.putObject({
       Key: 'key',
-      Body: Buffer.alloc(1024 * 1024 - 1), // works
+      Body: new Buffer(1024 * 1024 - 1), // works
       // Body: new Buffer(1024 * 1024), // doesn't work
       ContentType: 'binary/octet-stream'
     },
@@ -57,7 +57,7 @@ test('works with s3, body = 10 * 1024 ^ 2', function (t) {
 
   bucket.putObject({
       Key: 'key',
-      Body: Buffer.alloc(10 * 1024 * 1024), // doesn't work
+      Body: new Buffer(10 * 1024 * 1024), // doesn't work
       ContentType: 'binary/octet-stream'
     },
     function (err, resp) {
@@ -88,7 +88,7 @@ test('works with s3, body = 16 * 1024 ^ 2', function (t) {
 
   bucket.putObject({
       Key: 'key',
-      Body: Buffer.alloc(16 * 1024 * 1024), // doesn't work
+      Body: new Buffer(16 * 1024 * 1024), // doesn't work
       ContentType: 'binary/octet-stream'
     },
     function (err, resp) {