node.js - 查看管道错误中的管道数据

标签 node.js error-handling pipe

在以下代码块中,如何记录导致 JSONStream.parse 失败的管道数据?

data.pipe(JSONStream.parse('*'))
.on('error', () => {
    // here I'd like to see the data causing JOSONStream.parse to blow up
    reject("Error parsing the json!");
})
.pipe(objectStream);

我问,因为目前当它爆炸时,我收到这种错误消息,但没有关于 Invalid UTF-8 字符是什么的上下文:
Error: Invalid JSON (Invalid UTF-8 character at position 2397 in state STRING1)
        at Parser.proto.write (/var/www/data-site/pop-service/node_modules/JSONStream/node_modules/jsonparse/jsonparse.js:120:31)
        at Stream.<anonymous> (/var/www/data-site/pop-service/node_modules/JSONStream/index.js:23:12)
        at Stream.stream.write (/var/www/data-site/pop-service/node_modules/JSONStream/node_modules/through/index.js:26:11)
        at IncomingMessage.ondata (_stream_readable.js:536:20)
        at emitOne (events.js:82:20)
        at IncomingMessage.emit (events.js:169:7)
        at readableAddChunk (_stream_readable.js:153:18)
        at IncomingMessage.Readable.push (_stream_readable.js:111:10)
        at HTTPParser.parserOnBody (_http_common.js:124:22)
        at TLSSocket.socketOnData (_http_client.js:320:20)

类似于 .on('error', (data) => {...似乎不起作用

解决方案使用@dinchev 的回答
    //save the last chunk so that we can log it in case of parsing error
    let lastRetrievedChunk = '';
    data.on('data', (dd: any) => {
      lastRetrievedChunk = dd.toString();
    });

    let jsonParser = JSONStream.parse('*');
    jsonParser.on('error', (err: any) => {
      reject(err.stack + ' lastchunk = ' + lastRetrievedChunk);
    });
    data.pipe(jsonParser).pipe(objectStream);

最佳答案

它确实不起作用,因为它是事件驱动的过程。

您可以尝试将数据存储在变量中并将其传递给错误

var someString = '*';

data.pipe(JSONStream.parse(someString))
    .on('error', () => {
       console.log( someString );
       reject("Error parsing the json!");
    })
    .pipe(objectStream);

在任何时候,您还可以使用一些库,如 through2这可以帮助您制作一个记录管道数据的流。

关于node.js - 查看管道错误中的管道数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40007746/

相关文章:

angularjs - 如何在不使用 npm start 的情况下在生产中部署 angularjs 项目

python - 使用 python 管道 2 python 脚本

angularjs - NodeJS 周期性任务

node.js - 当我更改 wifi 网络时,Socket.io 连接不上

javascript - Promise.all 不要等待所有的 promise 来解决

php - PHP/Ajax匿名函数,迭代会导致错误? +如何在使用Ajax时显示标准PHP错误

angularjs - Angular $ watch空值错误

ios - 尝试将多个图像上传到Firebase : 2 Errors in SWIFT 4, FIREBASE 5.0.0

c++ - 父进程如何用一个管道向 n 个子进程发送消息?

Angular - 管道类型没有 'ɵmod' 属性