index.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. 'use strict';
  2. // Make a value ready for JSON.stringify() / process.send()
  3. module.exports = function (value) {
  4. if (typeof value === 'object') {
  5. return destroyCircular(value, []);
  6. }
  7. // People sometimes throw things besides Error objects, so...
  8. if (typeof value === 'function') {
  9. // JSON.stringify discards functions. We do to, unless a function is thrown directly.
  10. return '[Function: ' + (value.name || 'anonymous') + ']';
  11. }
  12. return value;
  13. };
  14. // https://www.npmjs.com/package/destroy-circular
  15. function destroyCircular(from, seen) {
  16. var to;
  17. if (Array.isArray(from)) {
  18. to = [];
  19. } else {
  20. to = {};
  21. }
  22. seen.push(from);
  23. Object.keys(from).forEach(function (key) {
  24. var value = from[key];
  25. if (typeof value === 'function') {
  26. return;
  27. }
  28. if (!value || typeof value !== 'object') {
  29. to[key] = value;
  30. return;
  31. }
  32. if (seen.indexOf(from[key]) === -1) {
  33. to[key] = destroyCircular(from[key], seen.slice(0));
  34. return;
  35. }
  36. to[key] = '[Circular]';
  37. });
  38. if (typeof from.name === 'string') {
  39. to.name = from.name;
  40. }
  41. if (typeof from.message === 'string') {
  42. to.message = from.message;
  43. }
  44. if (typeof from.stack === 'string') {
  45. to.stack = from.stack;
  46. }
  47. return to;
  48. }