如何查看大对象(如响应对象),太大,无法在CLI中使用。

问题描述 投票:0回答:1

我正在学习编码和NodeJS。有一件事我一直被卡住了,那就是试图学习响应对象。它是巨大的,当我 console.log()或 console.dir()它时,我无法消化所有的信息。

有一个工具非常方便,那就是Chrome JSON查看器扩展器。还有这个 jsonviewer.stack.hu 做了同样的事情,允许你发布JSON对象,并提供一个可读的对象视图。

不幸的是,它不接受常规对象(从我的CLI复制和粘贴的对象)。我试过在对象上使用JSON.stringfy(),但这个方法会剥离原始对象上90%的属性。

有没有一种简单的解决方案,可以查看CLI记录的对象,并能折叠和展开属性?

该对象在CLI中的记录如下。

    Response {
      _events: [Object: null prototype] {},
      _eventsCount: 0,
      _maxListeners: undefined,
      res: IncomingMessage {
        _readableState: ReadableState {
          objectMode: false,
          highWaterMark: 16384,
          buffer: BufferList { head: null, tail: null, length: 0 },
          length: 0,
          pipes: null,
          pipesCount: 0,
          flowing: true,
          ended: true,
          endEmitted: true,
          reading: false,
          sync: true,
          needReadable: false,
          emittedReadable: false,
          readableListening: false,
          resumeScheduled: false,
          paused: false,
          emitClose: true,
          autoDestroy: false,
          destroyed: false,
          defaultEncoding: 'utf8',
          awaitDrain: 0,
          readingMore: true,
          decoder: [StringDecoder],
          encoding: 'utf8'
        },
        readable: false,
        _events: [Object: null prototype] {
          end: [Array],
          data: [Array],
          error: [Array],
          close: [Function: bound emit]
        },
        _eventsCount: 4,
        _maxListeners: undefined,
        socket: Socket {
          connecting: false,
          _hadError: false,
          _parent: null,
          _host: null,
          _readableState: [ReadableState],
          readable: true,
          _events: [Object: null prototype],
          _eventsCount: 6,
          _maxListeners: undefined,
          _writableState: [WritableState],
          writable: false,
          allowHalfOpen: false,
          _sockname: null,
          _pendingData: null,
          _pendingEncoding: '',
          server: null,
          _server: null,
          parser: null,
          _httpMessage: [ClientRequest],
          [Symbol(asyncId)]: 150,
          [Symbol(kHandle)]: [TCP],
          [Symbol(lastWriteQueueSize)]: 0,
          [Symbol(timeout)]: null,
          [Symbol(kBuffer)]: null,
          [Symbol(kBufferCb)]: null,
          [Symbol(kBufferGen)]: null,
          [Symbol(kBytesRead)]: 0,
          [Symbol(kBytesWritten)]: 0
        },
        connection: Socket {
          connecting: false,
          _hadError: false,
          _parent: null,
          _host: null,
          _readableState: [ReadableState],
          readable: true,
          _events: [Object: null prototype],
          _eventsCount: 6,
          _maxListeners: undefined,
          _writableState: [WritableState],
          writable: false,
          allowHalfOpen: false,
          _sockname: null,
          _pendingData: null,
          _pendingEncoding: '',
          server: null,
          _server: null,
          parser: null,
          _httpMessage: [ClientRequest],
          [Symbol(asyncId)]: 150,
          [Symbol(kHandle)]: [TCP],
          [Symbol(lastWriteQueueSize)]: 0,
          [Symbol(timeout)]: null,
          [Symbol(kBuffer)]: null,
          [Symbol(kBufferCb)]: null,
          [Symbol(kBufferGen)]: null,
          [Symbol(kBytesRead)]: 0,
          [Symbol(kBytesWritten)]: 0
        },
        httpVersionMajor: 1,
        httpVersionMinor: 1,
        httpVersion: '1.1',
        complete: true,
        headers: {
          'x-powered-by': 'Express',
          'set-cookie': [Array],
          location: '/',
          vary: 'Accept',
          'content-type': 'text/plain; charset=utf-8',
          'content-length': '23',
          date: 'Sat, 09 May 2020 09:52:40 GMT',
          connection: 'close'
        },
        rawHeaders: [
          'X-Powered-By',
          'Express',
          'Set-Cookie',
          'access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiYWRtaW4iOnRydWUsInVzZXJpZCI6MSwiaWF0IjoxNTg5MDE3OTYwfQ.x4sRUhSqMaTFt2S3mrv6k3LOUecIgUJ4Cy8zWvdemss; Max-Age=3600; Path=/; Expires=Sat, 09 May 2020 10:52:40 GMT; HttpOnly',
          'Location',
          '/',
          'Vary',
          'Accept',
          'Content-Type',
          'text/plain; charset=utf-8',
          'Content-Length',
          '23',
          'Date',
          'Sat, 09 May 2020 09:52:40 GMT',
          'Connection',
          'close'
        ],
        trailers: {},
        rawTrailers: [],
        aborted: false,
        upgrade: false,
        url: '',
        method: null,
        statusCode: 302,
        statusMessage: 'Found',
        client: Socket {
          connecting: false,
          _hadError: false,
          _parent: null,
          _host: null,
          _readableState: [ReadableState],
          readable: true,
          _events: [Object: null prototype],
          _eventsCount: 6,
          _maxListeners: undefined,
          _writableState: [WritableState],
          writable: false,
          allowHalfOpen: false,
          _sockname: null,
          _pendingData: null,
          _pendingEncoding: '',
          server: null,
          _server: null,
          parser: null,
          _httpMessage: [ClientRequest],
          [Symbol(asyncId)]: 150,
          [Symbol(kHandle)]: [TCP],
          [Symbol(lastWriteQueueSize)]: 0,
          [Symbol(timeout)]: null,
          [Symbol(kBuffer)]: null,
          [Symbol(kBufferCb)]: null,
          [Symbol(kBufferGen)]: null,
          [Symbol(kBytesRead)]: 0,
          [Symbol(kBytesWritten)]: 0
        },
        _consuming: false,
        _dumped: false,
        req: ClientRequest {
          _events: [Object: null prototype],
          _eventsCount: 3,
          _maxListeners: undefined,
          outputData: [],
          outputSize: 0,
          writable: true,
          _last: true,
          chunkedEncoding: false,
          shouldKeepAlive: false,
          useChunkedEncodingByDefault: true,
          sendDate: false,
          _removedConnection: false,
          _removedContLen: false,
          _removedTE: false,
          _contentLength: 39,
          _hasBody: true,
          _trailer: '',
          finished: true,
          _headerSent: true,
          socket: [Socket],
          connection: [Socket],
          _header: 'POST /authenticate HTTP/1.1\r\n' +
            'Host: 127.0.0.1:41185\r\n' +
            'Accept-Encoding: gzip, deflate\r\n' +
            'User-Agent: node-superagent/3.8.3\r\n' +
            'Content-Type: application/json\r\n' +
            'Content-Length: 39\r\n' +
            'Connection: close\r\n' +
            '\r\n',
          _onPendingData: [Function: noopPendingOutput],
          agent: [Agent],
          socketPath: undefined,
          method: 'POST',
          path: '/authenticate',
          _ended: true,
          res: [Circular],
          aborted: false,
          timeoutCb: null,
          upgradeOrConnect: false,
          parser: null,
          maxHeadersCount: null,
          [Symbol(kNeedDrain)]: false,
          [Symbol(isCorked)]: false,
          [Symbol(kOutHeaders)]: [Object: null prototype]
        },
        text: 'Found. Redirecting to /'
      },
      request: Test {
        _events: [Object: null prototype] {},
        _eventsCount: 0,
        _maxListeners: undefined,
        _agent: false,
        _formData: null,
        method: 'POST',
        url: 'http://127.0.0.1:41185/authenticate',
        _header: {
          'user-agent': 'node-superagent/3.8.3',
          'content-type': 'application/json'
        },
        header: {
          'User-Agent': 'node-superagent/3.8.3',
          'Content-Type': 'application/json'
        },
        writable: true,
        _redirects: 1,
        _maxRedirects: 0,
        cookies: '',
        qs: {},
        _query: [],
        qsRaw: [],
        _redirectList: [],
        _streamRequest: false,
        _buffer: true,
        app: Server {
          _events: [Object: null prototype],
          _eventsCount: 2,
          _maxListeners: undefined,
          _connections: 0,
          _handle: null,
          _usingWorkers: false,
          _workers: [],
          _unref: false,
          allowHalfOpen: true,
          pauseOnConnect: false,
          httpAllowHalfOpen: false,
          timeout: 120000,
          keepAliveTimeout: 5000,
          maxHeadersCount: null,
          headersTimeout: 40000,
          _connectionKey: '6::::0',
          [Symbol(IncomingMessage)]: [Function: IncomingMessage],
          [Symbol(ServerResponse)]: [Function: ServerResponse],
          [Symbol(asyncId)]: 148
        },
        _asserts: [ [Function: bound ] ],
        _server: Server {
          _events: [Object: null prototype],
          _eventsCount: 2,
          _maxListeners: undefined,
          _connections: 0,
          _handle: null,
          _usingWorkers: false,
          _workers: [],
          _unref: false,
          allowHalfOpen: true,
          pauseOnConnect: false,
          httpAllowHalfOpen: false,
          timeout: 120000,
          keepAliveTimeout: 5000,
          maxHeadersCount: null,
          headersTimeout: 40000,
          _connectionKey: '6::::0',
          [Symbol(IncomingMessage)]: [Function: IncomingMessage],
          [Symbol(ServerResponse)]: [Function: ServerResponse],
          [Symbol(asyncId)]: 148
        },
        _data: { username: 'admin', password: 'admin' },
        req: ClientRequest {
          _events: [Object: null prototype],
          _eventsCount: 3,
          _maxListeners: undefined,
          outputData: [],
          outputSize: 0,
          writable: true,
          _last: true,
          chunkedEncoding: false,
          shouldKeepAlive: false,
          useChunkedEncodingByDefault: true,
          sendDate: false,
          _removedConnection: false,
          _removedContLen: false,
          _removedTE: false,
          _contentLength: 39,
          _hasBody: true,
          _trailer: '',
          finished: true,
          _headerSent: true,
          socket: [Socket],
          connection: [Socket],
          _header: 'POST /authenticate HTTP/1.1\r\n' +
            'Host: 127.0.0.1:41185\r\n' +
            'Accept-Encoding: gzip, deflate\r\n' +
            'User-Agent: node-superagent/3.8.3\r\n' +
            'Content-Type: application/json\r\n' +
            'Content-Length: 39\r\n' +
            'Connection: close\r\n' +
            '\r\n',
          _onPendingData: [Function: noopPendingOutput],
          agent: [Agent],
          socketPath: undefined,
          method: 'POST',
          path: '/authenticate',
          _ended: true,
          res: [IncomingMessage],
          aborted: false,
          timeoutCb: null,
          upgradeOrConnect: false,
          parser: null,
          maxHeadersCount: null,
          [Symbol(kNeedDrain)]: false,
          [Symbol(isCorked)]: false,
          [Symbol(kOutHeaders)]: [Object: null prototype]
        },
        protocol: 'http:',
        host: '127.0.0.1:41185',
        _endCalled: true,
        _callback: [Function],
        res: IncomingMessage {
          _readableState: [ReadableState],
          readable: false,
          _events: [Object: null prototype],
          _eventsCount: 4,
          _maxListeners: undefined,
          socket: [Socket],
          connection: [Socket],
          httpVersionMajor: 1,
          httpVersionMinor: 1,
          httpVersion: '1.1',
          complete: true,
          headers: [Object],
          rawHeaders: [Array],
          trailers: {},
          rawTrailers: [],
          aborted: false,
          upgrade: false,
          url: '',
          method: null,
          statusCode: 302,
          statusMessage: 'Found',
          client: [Socket],
          _consuming: false,
          _dumped: false,
          req: [ClientRequest],
          text: 'Found. Redirecting to /'
        },
        response: [Circular],
        called: true
      },
      req: ClientRequest {
        _events: [Object: null prototype] {
          drain: [Function],
          error: [Function],
          prefinish: [Function: requestOnPrefinish]
        },
        _eventsCount: 3,
        _maxListeners: undefined,
        outputData: [],
        outputSize: 0,
        writable: true,
        _last: true,
        chunkedEncoding: false,
        shouldKeepAlive: false,
        useChunkedEncodingByDefault: true,
        sendDate: false,
        _removedConnection: false,
        _removedContLen: false,
        _removedTE: false,
        _contentLength: 39,
        _hasBody: true,
        _trailer: '',
        finished: true,
        _headerSent: true,
        socket: Socket {
          connecting: false,
          _hadError: false,
          _parent: null,
          _host: null,
          _readableState: [ReadableState],
          readable: true,
          _events: [Object: null prototype],
          _eventsCount: 6,
          _maxListeners: undefined,
          _writableState: [WritableState],
          writable: false,
          allowHalfOpen: false,
          _sockname: null,
          _pendingData: null,
          _pendingEncoding: '',
          server: null,
          _server: null,
          parser: null,
          _httpMessage: [Circular],
          [Symbol(asyncId)]: 150,
          [Symbol(kHandle)]: [TCP],
          [Symbol(lastWriteQueueSize)]: 0,
          [Symbol(timeout)]: null,
          [Symbol(kBuffer)]: null,
          [Symbol(kBufferCb)]: null,
          [Symbol(kBufferGen)]: null,
          [Symbol(kBytesRead)]: 0,
          [Symbol(kBytesWritten)]: 0
        },
        connection: Socket {
          connecting: false,
          _hadError: false,
          _parent: null,
          _host: null,
          _readableState: [ReadableState],
          readable: true,
          _events: [Object: null prototype],
          _eventsCount: 6,
          _maxListeners: undefined,
          _writableState: [WritableState],
          writable: false,
          allowHalfOpen: false,
          _sockname: null,
          _pendingData: null,
          _pendingEncoding: '',
          server: null,
          _server: null,
          parser: null,
          _httpMessage: [Circular],
          [Symbol(asyncId)]: 150,
          [Symbol(kHandle)]: [TCP],
          [Symbol(lastWriteQueueSize)]: 0,
          [Symbol(timeout)]: null,
          [Symbol(kBuffer)]: null,
          [Symbol(kBufferCb)]: null,
          [Symbol(kBufferGen)]: null,
          [Symbol(kBytesRead)]: 0,
          [Symbol(kBytesWritten)]: 0
        },
        _header: 'POST /authenticate HTTP/1.1\r\n' +
          'Host: 127.0.0.1:41185\r\n' +
          'Accept-Encoding: gzip, deflate\r\n' +
          'User-Agent: node-superagent/3.8.3\r\n' +
          'Content-Type: application/json\r\n' +
          'Content-Length: 39\r\n' +
          'Connection: close\r\n' +
          '\r\n',
        _onPendingData: [Function: noopPendingOutput],
        agent: Agent {
          _events: [Object: null prototype],
          _eventsCount: 1,
          _maxListeners: undefined,
          defaultPort: 80,
          protocol: 'http:',
          options: [Object],
          requests: {},
          sockets: [Object],
          freeSockets: {},
          keepAliveMsecs: 1000,
          keepAlive: false,
          maxSockets: Infinity,
          maxFreeSockets: 256
        },
        socketPath: undefined,
        method: 'POST',
        path: '/authenticate',
        _ended: true,
        res: IncomingMessage {
          _readableState: [ReadableState],
          readable: false,
          _events: [Object: null prototype],
          _eventsCount: 4,
          _maxListeners: undefined,
          socket: [Socket],
          connection: [Socket],
          httpVersionMajor: 1,
          httpVersionMinor: 1,
          httpVersion: '1.1',
          complete: true,
          headers: [Object],
          rawHeaders: [Array],
          trailers: {},
          rawTrailers: [],
          aborted: false,
          upgrade: false,
          url: '',
          method: null,
          statusCode: 302,
          statusMessage: 'Found',
          client: [Socket],
          _consuming: false,
          _dumped: false,
          req: [Circular],
          text: 'Found. Redirecting to /'
        },
        aborted: false,
        timeoutCb: null,
        upgradeOrConnect: false,
        parser: null,
        maxHeadersCount: null,
        [Symbol(kNeedDrain)]: false,
        [Symbol(isCorked)]: false,
        [Symbol(kOutHeaders)]: [Object: null prototype] {
          host: [Array],
          'accept-encoding': [Array],
          'user-agent': [Array],
          'content-type': [Array],
          'content-length': [Array]
        }
      },
      text: 'Found. Redirecting to /',
      body: {},
      files: undefined,
      buffered: true,
      headers: {
        'x-powered-by': 'Express',
        'set-cookie': [
          'access_token=kkkhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiYWRtaW4iOnRydWUsInVzZXJpZCI6MSwiaWF0IjoxNTg5MDE3OTYwfQ.x4sRUhSqMaTFt2S3mrv6k3LOUecIgUJ4Cy8zWvdemss; Max-Age=3600; Path=/; Expires=Sat, 09 May 2020 10:52:40 GMT; HttpOnly'
        ],
        location: '/',
        vary: 'Accept',
        'content-type': 'text/plain; charset=utf-8',
        'content-length': '23',
        date: 'Sat, 09 May 2020 09:52:40 GMT',
        connection: 'close'
      },
      header: {
        'x-powered-by': 'Express',
        'set-cookie': [
          'access_token=lkJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiYWRtaW4iOnRydWUsInVzZXJpZCI6MSwiaWF0IjoxNTg5MDE3OTYwfQ.x4sRUhSqMaTFt2S3mrv6k3LOUecIgUJ4Cy8zWvdemrr; Max-Age=3600; Path=/; Expires=Sat, 09 May 2020 10:52:40 GMT; HttpOnly'
        ],
        location: '/',
        vary: 'Accept',
        'content-type': 'text/plain; charset=utf-8',
        'content-length': '23',
        date: 'Sat, 09 May 2020 09:52:40 GMT',
        connection: 'close'
      },
      statusCode: 302,
      status: 302,
      statusType: 3,
      info: false,
      ok: false,
      redirect: true,
      clientError: false,
      serverError: false,
      error: false,
      created: false,
      accepted: false,
      noContent: false,
      badRequest: false,
      unauthorized: false,
      notAcceptable: false,
      forbidden: false,
      notFound: false,
      unprocessableEntity: false,
      type: 'text/plain',
      charset: 'utf-8',
      links: {},
      setEncoding: [Function: bound ],
      redirects: []
    }
javascript node.js json object response
1个回答
0
投票

好了,我已经有了 a 解决方案,尽管是一个非常啰嗦的解决方案。

基本上我克隆了响应对象,然后将所有属性转换为enumerable。然后JSON.stringify仍然不能在新对象上执行,因为对象中包含循环引用。我们必须提供一个函数来替换循环引用(我不确定......也许是 "undefined"? 然后我们就可以将其字符串化。我已经记录了这个对象,然后复制并粘贴到JSON浏览器中。我想问题解决了--但我想有一个更简洁的解决方案。

           let resclone = {...res}
            //console.log(resclone);

            const toEnumerable = (obj) => {
                return Object.fromEntries(
                  Object.getOwnPropertyNames(obj).map(prop => [prop, obj[prop]])
                );
              };

              var enumerated = toEnumerable(resclone)

              const getCircularReplacer = () => {
                const seen = new WeakSet();
                return (key, value) => {
                  if (typeof value === "object" && value !== null) {
                    if (seen.has(value)) {
                      return;
                    }
                    seen.add(value);
                  }
                  return value;
                };
              };

              let stringify = JSON.stringify(enumerated, getCircularReplacer());
              console.log(stringify);
© www.soinside.com 2019 - 2024. All rights reserved.