Created
August 26, 2010 21:03
-
-
Save samsonjs/552244 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
////////////////////////////////////////////// | |
// REDUCTION: http://gist.github.com/553200 | |
////////////////////////////////////////////// | |
// Somehow we've managed to push the right buttons causing Node to get | |
// into a broken state. After hitting our web server anywhere from | |
// 5-5000 times JSON.stringify begins to produce corrupt output. Where | |
// the ascii chars 'null' should appear for null values, | |
// JSON.stringify instead emits these 4 bytes: \002\000\000\000 | |
// | |
// The bug occurs with Node v0.1.101 up till v0.2.0, on Mac OS X | |
// 10.6.4 (amd64) and Ubuntu 10.04 (x86). We can't reproduce it on | |
// v0.1.100. | |
// | |
// Until we can isolate a test case NodeMachine[1] is one variable in | |
// the equation. We haven't been able to rule it out as a factor in | |
// triggering the bug. | |
// | |
// [1] http://github.com/tautologistics/nodemachine | |
function jsonResponse(code, object) { | |
var status, | |
body = '', | |
headers = {'content-length': 0}, | |
wrappedObject; | |
if (typeof object === 'number') | |
status = code >= 200 && code < 300 ? 'ok' : 'fail'; | |
else { | |
status = code; | |
code = object ? 200 : 204; | |
} | |
if (object) { | |
if (Array.isArray(object)) | |
wrappedObject = {status: status, data: object}; | |
else | |
wrappedObject = mergeObjects({status: status}, object); | |
body = JSON.stringify(wrappedObject); | |
// This if block detects corruption in the resulting JSON | |
if (body.match(/\000/)) { | |
console.log('JSON.stringify is producing corrupt data!') | |
var body2 = JSON.stringify(wrappedObject); | |
if (body2.match(/\000/)) { | |
console.log('JSON.stringify definitely corrupting data') | |
} else { | |
console.log('this else branch is never taken') | |
} | |
} | |
headers['content-length'] = body.length; | |
headers['content-type'] = 'application/json'; | |
} | |
return [code, headers, body]; | |
}; | |
function updateObject(target, source) { | |
for (key in source) { | |
if (source.hasOwnProperty(key)) { | |
target[key] = source[key]; | |
} | |
} | |
return target; | |
} | |
function mergeObjects(a, b) { | |
var obj = updateObject({}, a); | |
return updateObject(obj, b); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment