How can I create a readable stream from a writable stream? (Node.js)

I create Excel data on the fly using Exceljs

I want to store this information in memory, and then send it to the user using Koa.

Method writefor Exceljs expects writeableStream:

workbook.xlsx.write(writableStream, options)

BUT KOA expects a readable stream:

response.body = readableStream

I know that I can transfer a readable stream to a writeable stream, but how can I do the opposite? I want Exceljs to write to a writeable stream and read Coa from one stream. I'm so upset with the threading API!

Among the 20 other things I tried this:

const ReadableStream = require("memory-streams").ReadableStream

const reader = new ReadableStream()

const writer = new stream.Writable({
    write: function(chunk, encoding, next) {
        console.log(chunk.toString())
        // reader.push(chunk, encoding)
        next()
    }
})

const reader = new MemoryStream(null, {readable: true})
// reader.write = reader.unshift
const writer = reader

workbook.xlsx.write(writer, {})
return reader

But this will not work, I get some strange error in that I cannot write a thread that is closed. However, even if I handle this error, my Excel file does not open.

So how can I make a readable stream from a writeable stream?

+4
2

. , .

stream = new require('stream').Transform()
stream._transform = function (chunk,encoding,done) 
{
    this.push(chunk)
    done()
}
+1

, , . , .

QRCode-, QRGode png- var (ex: userId) stream.Writable → AWS S3 stream.Readable.

import QRCode from 'qrcode';
import AWS from 'aws-sdk';
import { Transform } from 'stream';

const userId = 'userIdString';

// AWS Config, import this from a safe place!!!
AWS.config.update({
  accessKeyId: 'xxxxxxxxxx',
  secretAccessKey: 'xxxxxxxxx',
  region: 'xxxxxxx',
});

const s3 = new AWS.S3({ apiVersion: '2006-03-01' });

// Create Stream, Writable AND Readable
const inoutStream = new Transform({
  transform(chunk, encoding, callback) {
    this.push(chunk);
    callback();
  },
});

// Need writable stream
QRCode.toFileStream(inoutStream, userId);

//Just to check
inoutStream.on('finish', () => {
  console.log('finished writing');
});

// Need readable stream
  s3.upload(
    {
      Bucket: 'myBucket',
      Key: `QR_${userId}.png`,
      Body: inoutStream,
      // ACL: 'public-read',
      ContentType: 'image/png',
    },
    (err, data) => {
      console.log(err, data);
    },
  )
  .on('httpUploadProgress', (evt) => {
    console.log(evt);
  })
  .send((err, data) => {
    console.log(err, data);
  });

.

0

Source: https://habr.com/ru/post/1629957/


All Articles