【问题标题】:Code after pipe is not executing in node js readstream管道后的代码未在节点js readstream中执行
【发布时间】:2021-02-05 12:45:15
【问题描述】:

我有如下 JSON 客户.json

   {
    "customers":[
          { "name": "customer1"},
          { "name": "customer2"},
          { "name": "customer3"}
         ]
   }

var fs = require('fs'),
    JSONStream = require('JSONStream'),
    es = require('event-stream');

async function run(){
    var getStream = function () {
        var jsonData = 'customers.json',
            stream = fs.createReadStream(jsonData, { encoding: 'utf8' }),
            parser = JSONStream.parse('customers.*');
        return stream.pipe(parser);
    };
    var arr = [];
    getStream()
        .on('data', function (chunk) {
            arr.push(chunk);
        })
        .on('end', function () {
            console.log('All the data in the file has been read' + arr.length);
        })
        .on('close', function (err) {
            console.log('Stream has been Closed');
        });

        console.log('end run()');
}

async function main(){
    run().then(function(){
        console.log('In then');
    }).catch(function(){
        console.log('In catch');
    })
}

main();

在输出中为什么在“end”、“close”之前打印“In then”。事件。

如何在“end”、“close”事件后获取“In then”或In Catch。

我如何以同步方式执行 run() 方法。

【问题讨论】:

  • JSONStream 主要是为大型文件设计的,您希望在其中解析文件的某些部分而不必解析整个文件。这里是这样吗?还是我的回答足够了?
  • @LindaPaiste,没错,我有巨大的 json,所以我无法读取内存中的整个文件。所以你的回答是不够的。

标签: javascript node.js asynchronous pipe jsonstream


【解决方案1】:

当异步运行函数时,对console 的调用不一定按顺序进行。如果它是异步的,则不应依赖按顺序执行的任何操作。

如果你想让run() 同步,它实际上比你现在做的要简单得多,因为你根本不需要使用流。您只需调用 fs.readFileSync 从本地 json 文件加载数据。 This article 解释了一些差异。

var fs = require('fs');

function run() {
  const rawData = fs.readFileSync("customers.json"); // Buffer
  const jsonData = JSON.parse(rawData); // object
  jsonData.customers.forEach( o => console.log(o.name) );
}

function main() {
  run();
  console.log("done");
}

main();

控制台输出:

customer1
customer2
customer3
done

【讨论】:

    猜你喜欢
    • 2021-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 2018-12-26
    • 1970-01-01
    相关资源
    最近更新 更多