Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express generate and return QR code on GET request

I am trying to generate a QR-code on an express request. It takes the value from the URL parameter, and returns the QR-Code using a filestream as a raw image.

const express = require('express');
const router = express.Router();
const QRCode = require('qrcode');

router.get('/qr/:content', function(req, res, next){
let content = req.params.content

// Filestream goes here

})

This is how I tried to do it, however I have never worked with filestreams and I cannot get it working:

let code = QRCode.toFileStream(new stream.Writable, conent)
code.pipe(res);

This is the library I'm using: https://www.npmjs.com/package/qrcode

like image 212
Leonard Niehaus Avatar asked Jan 22 '20 16:01

Leonard Niehaus


1 Answers

Try this code:

import QRCode from 'qrcode';
import { PassThrough } from 'stream';


router.get('/qr/:content', async (req, res, next) => {
    try{
        const content = req.params.content;            
        const qrStream = new PassThrough();
        const result = await QRCode.toFileStream(qrStream, content,
                    {
                        type: 'png',
                        width: 200,
                        errorCorrectionLevel: 'H'
                    }
                );

        qrStream.pipe(res);
    } catch(err){
        console.error('Failed to return content', err);
    }
}
like image 110
Moose on the Loose Avatar answered Nov 15 '22 07:11

Moose on the Loose