From 591e757b35313f91a0d6f0881dbe706f270ce3e9 Mon Sep 17 00:00:00 2001 From: Andrea Giammarchi Date: Wed, 29 Nov 2017 11:59:05 -0300 Subject: [PATCH] Enable circular references while scanning for binary In order to avoid issues with circular references, this PR would like to avoid recursive scans so that it is possible to send data via CircularJSON, as mentioned in the following PR: https://github.com/socketio/socket.io-parser/pull/80 --- index.js | 18 +++++++++++++----- test.js | 25 +++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 5 deletions(-) diff --git a/index.js b/index.js index 395036e..c4cdc97 100644 --- a/index.js +++ b/index.js @@ -10,7 +10,9 @@ var isArray = require('isarray'); * Module exports. */ -module.exports = hasBinary; +module.exports = function hasBinaryCircular (obj) { + return hasBinary(obj, []); +}; /** * Checks for binary data. @@ -21,14 +23,20 @@ module.exports = hasBinary; * @api public */ -function hasBinary (obj) { +function hasBinary (obj, known) { if (!obj || typeof obj !== 'object') { return false; } + if (known.indexOf(obj) >= 0) { + return false; + } + + known.push(obj); + if (isArray(obj)) { for (var i = 0, l = obj.length; i < l; i++) { - if (hasBinary(obj[i])) { + if (hasBinary(obj[i], known)) { return true; } } @@ -45,11 +53,11 @@ function hasBinary (obj) { // see: https://github.com/Automattic/has-binary/pull/4 if (obj.toJSON && typeof obj.toJSON === 'function') { - return hasBinary(obj.toJSON()); + return hasBinary(obj.toJSON(), known); } for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) { + if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key], known)) { return true; } } diff --git a/test.js b/test.js index 8e65ff3..127fac5 100644 --- a/test.js +++ b/test.js @@ -79,4 +79,29 @@ describe('has-binarydata', function () { assert(!hasBinary(global.Blob)); }); } + + it('should work with recursive structures and no blobs', function () { + var child = { + foo: 'bar' + }; + var parent = { + zoo: 'gar', + child: child + }; + child.parent = parent; + assert(!hasBinary(child)); + }); + + it('should work with recursive structures and blobs', function () { + var child = { + foo: 'bar' + }; + var parent = { + zoo: 'gar', + child: child, + blob: new Buffer('xxx') + }; + child.parent = parent; + assert(hasBinary(child)); + }); });