簡體   English   中英

管道后的代碼未在節點 js readstream 中執行

[英]Code after pipe is not executing in node js readstream

我有如下的 JSONcustomers.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();

在輸出中為什么“In then”在“end”,“close”之前打印。 事件。

如何在“結束”、“關閉”事件之后獲得“In then”或“In Catch”。

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

異步運行函數時,不一定會按順序調用console 如果它是異步的,你不應該依賴於按順序完成的任何事情。

如果你想讓run()同步,它實際上比你現在做的要簡單得多,因為你根本不需要使用流。 您可以調用fs.readFileSync從本地 json 文件加載數據。 本文解釋了一些差異。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM