From 0af96f6ba02f24a8350153629292792c017f9bd8 Mon Sep 17 00:00:00 2001 From: Kostas Chatzikokolakis Date: Fri, 8 Jan 2016 18:04:57 +0100 Subject: [PATCH 1/2] add test for object whose toJSON() returns a Buffer --- test.js | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/test.js b/test.js index c6bd5aa..f211e95 100644 --- a/test.js +++ b/test.js @@ -29,6 +29,11 @@ describe('has-binarydata', function(){ assert(hasBinary(ob)); }); + it('should work with an object whose toJSON() returns a buffer', function() { + var ob = {a: 'a', b: [], c: 1234, toJSON: function() { return new Buffer('abc') }}; + assert(hasBinary(ob)); + }); + it('should work with null', function() { assert(!hasBinary(null)); }); From 23ee175e7760e6ccea96858536c09e7625a657c0 Mon Sep 17 00:00:00 2001 From: Kostas Chatzikokolakis Date: Fri, 8 Jan 2016 18:08:12 +0100 Subject: [PATCH 2/2] fix the case when toJSON() returns Buffer --- index.js | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/index.js b/index.js index 434ccfa..082f41d 100644 --- a/index.js +++ b/index.js @@ -22,7 +22,7 @@ module.exports = hasBinary; function hasBinary(data) { - function _hasBinary(obj) { + function _hasBinary(obj, afterToJSON) { if (!obj) return false; if ( (global.Buffer && global.Buffer.isBuffer && global.Buffer.isBuffer(obj)) || @@ -41,8 +41,9 @@ function hasBinary(data) { } } else if (obj && 'object' == typeof obj) { // see: https://github.com/Automattic/has-binary/pull/4 - if (obj.toJSON && 'function' == typeof obj.toJSON) { - obj = obj.toJSON(); + // also: toJSON() can return any type. Restart the check, but don't call toJSON twice + if (!afterToJSON && obj.toJSON && 'function' == typeof obj.toJSON) { + return _hasBinary(obj.toJSON(), true); } for (var key in obj) {