Skip to content

Instantly share code, notes, and snippets.

@itayw
Created December 30, 2013 07:13
Show Gist options
  • Save itayw/8178824 to your computer and use it in GitHub Desktop.
Save itayw/8178824 to your computer and use it in GitHub Desktop.
Async JSON.stringify and JSON.parse
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