Code after pipe is not executing in node js readstream

468 views Asked by At

I have JSON as below customers.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 output why "In then" printing before "end", "close". event.

How to get "In then" or In Catch after "end", "close" event.

How i can execute run() method in synchronous way.

1

There are 1 answers

0
Linda Paiste On

When running function asynchronously, calls to the console won't necessarily be made in order. You should not rely on anything being done in order if it's async.

If you want to make run() synchronous, it's actually much much simpler than what you're doing now because you don't need to use streams at all. You can just call fs.readFileSync to load the data from a local json file. This article explains some of the differences.

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();

Console output:

customer1
customer2
customer3
done