Skip to content

Commit 129d460

Browse files
committed
Add space to JSON.stringify() for Node 0.10 issue
Fixes #3
1 parent bc8e811 commit 129d460

File tree

2 files changed

+12
-5
lines changed

2 files changed

+12
-5
lines changed

index.js

+11-4
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ See the accompanying LICENSE file for terms.
66

77
'use strict';
88

9-
var util = require('util');
9+
var isRegExp = require('util').isRegExp;
1010

1111
module.exports = serialize;
1212

@@ -24,6 +24,13 @@ var UNICODE_CHARS = {
2424
'\u2029': '\\u2029'
2525
};
2626

27+
// There's an issue with Node 0.10 (V8 3.14.5.9) which causes `JSON.stringify()`
28+
// and the subsequent `str.replace()` call to take over 100x more time than when
29+
// a the `JSON.stringify()` replacer function is used and the data being
30+
// serialized is very large (500KB). A remedy to this is setting the
31+
// `JSON.stringify()` `space` option to a truthy value.
32+
var SPACE = 2;
33+
2734
function serialize(obj) {
2835
var functions = [],
2936
regexps = [],
@@ -37,12 +44,12 @@ function serialize(obj) {
3744
return '@__FUNCTION_' + (functions.push(value) - 1) + '__@';
3845
}
3946

40-
if (util.isRegExp(value)) {
47+
if (typeof value === 'object' && isRegExp(value)) {
4148
return '@__REGEXP_' + (regexps.push(value) - 1) + '__@';
4249
}
4350

4451
return value;
45-
});
52+
}, SPACE);
4653

4754
// Protects against `JSON.stringify()` returning `undefined`, by serializing
4855
// to the literal string: "undefined".
@@ -57,7 +64,7 @@ function serialize(obj) {
5764
return UNICODE_CHARS[unsafeChar];
5865
});
5966

60-
if (!(functions.length || regexps.length)) {
67+
if (functions.length === 0 && regexps.length === 0) {
6168
return str;
6269
}
6370

test/unit/serialize.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ describe('serialize( obj )', function () {
4646
});
4747

4848
it('should serialize JSON to a JSON string', function () {
49-
expect(serialize(data)).to.equal(JSON.stringify(data));
49+
expect(serialize(data)).to.equal(JSON.stringify(data, null, 2));
5050
});
5151

5252
it('should deserialize a JSON string to a JSON object', function () {

0 commit comments

Comments
 (0)