Shamoon97
Shamoon97

Reputation: 329

How to make reading a file using Stream work Synchronously in Node js?

Here is my code i want work this code in a way that readerstream1 will display all the contents of the file first then it will move towards readerstream2 without changing higherWaterMark. In simple words i want it to work synchronously Thanks

let readerstream1 = fs.createReadStream('shamoon.txt', { highWaterMark: 8 });
let readerstream2 = fs.createReadStream('shamoon1.txt', { highWaterMark: 8 });
let writestream = fs.createWriteStream('put.txt');

readerstream1.on('data', function(chunk) {
    console.log("ReadStream1 Chunk has been received " + chunk)
})
readerstream2.on('data', function(chunk) {
    console.log("ReadStream2 Chunk has been received " + chunk)
})

Upvotes: 1

Views: 1139

Answers (1)

eol
eol

Reputation: 24555

You can wrap the stream's processing in a promise and listen for the end-event where you resolve the promise. After awaiting this promise you can continue with the next one. Something like this which still needs error handling but should give you a start:

function getReadStreamPromise(filePath, opts) {
   return new Promise((resolve, reject) => {
      const readerstream = fs.createReadStream(filePath, opts);
      readerstream.on('data', (chunk) => {
         // handle chunk
      })
      readerstream.on('error', (err)=> {
         reject(err);
      })
      readerstream.on('end', () => {
         resolve();
      })

   })
}

async function processStreams() {
   await getReadStreamPromise('shamoon.txt', { highWaterMark: 8 });
   await getReadStreamPromise('shamoon1.txt', { highWaterMark: 8 });      
}

Note that you could simply use fs.promises.readFile to read the files asynchronously but sequentially:

async function processStreams() {
    const content = await fs.promises.readFile('shamoon.txt');
    const content2 = await fs.promises.readFile('shamoon1.txt');
    await fs.promises.writeFile('put.txt', "someContent");
}

Upvotes: 1

Related Questions