Created
December 30, 2013 07:13
-
-
Save itayw/8178824 to your computer and use it in GitHub Desktop.
Async JSON.stringify and JSON.parse
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
common.stringify = function (obj, callback) { | |
var errored = false; | |
if (!obj) | |
return callback(null, obj); | |
try { | |
var | |
expected = [], | |
es = require('event-stream'); | |
expected.push(obj); | |
es.connect( | |
es.readArray(expected), | |
JSONStream.stringify(), | |
es.writeArray(function (err, lines) { | |
lines = lines[0]; | |
lines = lines.substring(2); | |
return callback(null, lines); | |
}) | |
).on('error', function (err) { | |
if (!errored) { | |
errored = true; | |
return callback(err, obj); | |
} | |
}); | |
} | |
catch (ex) { | |
return callback(ex, obj); | |
} | |
}; | |
common.parse = function (string, callback) { | |
var errored = false; | |
if (!string || string == 'undefined') | |
return callback(null, string); | |
try { | |
var | |
expected = [], | |
es = require('event-stream'); | |
expected.push(string); | |
es.connect( | |
es.readArray(expected), | |
JSONStream.parse(/./), | |
es.writeArray(function (err, obj) { | |
return callback(err, obj[0]); | |
}) | |
).on('error', function (err) { | |
if (!errored) { | |
errored = true; | |
return callback(err, string); | |
} | |
}); | |
} | |
catch (ex) { | |
return callback(ex, string); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment