inspect.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. 'use strict'
  2. /*
  3. This file is a reduced and adapted version of the main lib/internal/util/inspect.js file defined at
  4. https://github.com/nodejs/node/blob/main/lib/internal/util/inspect.js
  5. Don't try to replace with the original file and keep it up to date with the upstream file.
  6. */
  7. module.exports = {
  8. format(format, ...args) {
  9. // Simplified version of https://nodejs.org/api/util.html#utilformatformat-args
  10. return format.replace(/%([sdifj])/g, function (...[_unused, type]) {
  11. const replacement = args.shift()
  12. if (type === 'f') {
  13. return replacement.toFixed(6)
  14. } else if (type === 'j') {
  15. return JSON.stringify(replacement)
  16. } else if (type === 's' && typeof replacement === 'object') {
  17. const ctor = replacement.constructor !== Object ? replacement.constructor.name : ''
  18. return `${ctor} {}`.trim()
  19. } else {
  20. return replacement.toString()
  21. }
  22. })
  23. },
  24. inspect(value) {
  25. // Vastly simplified version of https://nodejs.org/api/util.html#utilinspectobject-options
  26. switch (typeof value) {
  27. case 'string':
  28. if (value.includes("'")) {
  29. if (!value.includes('"')) {
  30. return `"${value}"`
  31. } else if (!value.includes('`') && !value.includes('${')) {
  32. return `\`${value}\``
  33. }
  34. }
  35. return `'${value}'`
  36. case 'number':
  37. if (isNaN(value)) {
  38. return 'NaN'
  39. } else if (Object.is(value, -0)) {
  40. return String(value)
  41. }
  42. return value
  43. case 'bigint':
  44. return `${String(value)}n`
  45. case 'boolean':
  46. case 'undefined':
  47. return String(value)
  48. case 'object':
  49. return '{}'
  50. }
  51. }
  52. }