Nodejs - How to show qr-image result in view

Morteza Ziyae picture Morteza Ziyae · Dec 15, 2014 · Viewed 9.9k times · Source

I use qr-image plugin for Nodejs to generate a QR code and it works pretty good.

The problem is showing result image in ejs.

var express = require('express');
var router = express.Router();
var qr = require('qr-image');

router.get('/', function(req, res) {
    var code = qr.image("text to show in qr", { type: 'png', ec_level: 'H', size: 10, margin: 0 });
    res.type('png');
    code.pipe(res);
    // res.render('index', { title: 'QR Page', qr: code });
});

When i uncomment last line, nodejs crashs. How to send code to view as a variable?

Update:

This code returns [object Object] in result page.

var code = qr.image("text to show in qr", { type: 'png', ec_level: 'H', size: 10, margin: 0 });
res.render('index', { title: 'QR Page', qr: code });

Also console.log(code) shows this:

{ _readableState:
   { highWaterMark: 16384,
     buffer: [],
     length: 0,
     pipes: null,
     pipesCount: 0,
     flowing: false,
     ended: false,
     endEmitted: false,
     reading: false,
     calledRead: false,
     sync: true,
     needReadable: false,
     emittedReadable: false,
     readableListening: false,
     objectMode: false,
     defaultEncoding: 'utf8',
     ranOut: false,
     awaitDrain: 0,
     readingMore: false,
     decoder: null,
     encoding: null },
  readable: true,
  domain: null,
  _events: {},
  _maxListeners: 10,
  _read: [Function] }

Answer

Paul picture Paul · Dec 15, 2014

You're trying to stuff a rendered image into a template engine; it's not going to work.

You should instead have an image tag in the template that points to a URL that responds with the image.

// Edit based on comment

router.get('/qr/:text', function(req,res){
   var code = qr.image(req.params.text, { type: 'png', ec_level: 'H', size: 10, margin: 0 });
   res.setHeader('Content-type', 'image/png');
   code.pipe(res);
}

Then in your html template, make an image tag with the src set to /qr/whatever text and you should be in good shape.