0

I would like the function below to return me the img so i can use it later. For now its only logged into console as:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHQAAAB0CAYAAABUmhYnAAAAAklEQVR4AewaftIAAAK0SURBVO3BQW7kQAwEwSxC//9yro88NSBIM2sTjIg/WGMUa5RijVKsUYo1SrFGKdYoxRqlWKMUa5RijVKsUYo1SrFGKdYoxRrl4qEkfJNKl4RO5SQJJypdEr5J5YlijVKsUYo1ysXLVN6UhCeScKJyh8qbkvCmYo1SrFGKNcrFhyXhDpU7VLok3JGETuWOJNyh8knFGqVYoxRrlIs/Lgmdyh1JmKRYoxRrlGKNcvHHqdyRhE5lkmKNUqxRijXKxYep/GZJ6FTuUPlNijVKsUYp1igXL0vCNyWhU+mS0Kl0SbgjCb9ZsUYp1ijFGiX+4A9LwptU/rJijVKsUYo1ysVDSehUuiScqHRJuEPljiTckYRO5SQJnUqXhBOVJ4o1SrFGKdYoFx+mcpKETuUkCd+kcpKEO1S6JLypWKMUa5RijXLxYUnoVDqVkyR8ksodSehUTpLwTcUapVijFGuUi4dUuiR0Kl0STlQ6lS4J/5NKl4QTlZMkvKlYoxRrlGKNEn/wRUnoVLoknKjckYROpUtCp9IloVP5zYo1SrFGKdYo8Qd/WBKeULkjCScqXRJOVN5UrFGKNUqxRrl4KAnfpHKicpKELgmdyhNJ6FS+qVijFGuUYo1y8TKVNyXhiSR0KidJ6FQ6lS4JJ0m4Q+WJYo1SrFGKNcrFhyXhDpU7VLokdConSehU7lDpknCi8knFGqVYoxRrlIs/LgknSehUOpWTJJyonKh0SehU3lSsUYo1SrFGuRhGpUvCSRI6lROVO5LQqXxSsUYp1ijFGuXiw1Q+SeVE5Y4kvEnlJAmdyhPFGqVYoxRrlIuXJeGbknCi0iWhU+mScEcSOpUuCZ1Kp/KmYo1SrFGKNUr8wRqjWKMUa5RijVKsUYo1SrFGKdYoxRqlWKMUa5RijVKsUYo1SrFGKdYo/wCSxQr0ueVFqAAAAABJRU5ErkJggg==

const QRCode = require('qrcode')

function getData(){
    QRCode.toDataURL('some string', function (err, img) {
        console.log(img)
    })
}

getData()
Patriks
  • 3
  • 1

1 Answers1

0

You need to assign the data to a variable after qrcode.toDataUrl() has completed. You can do that in the callback you currently have, or you can use .then(x => { }); since one of the overlaods for toDataUrl() returns a promise.

const QRCode = require('qrcode')

var data;

QRCode.toDataURL('some string').then(qr => {
    data = qr; // After toDataUrl is finished, the qr data is assigned to the data variable
});
JCH
  • 170
  • 11
  • Thank you for your answer. I'm still not sure because its not working for me. I'm trying to build a function which returns the qr but i'm getting undefined or Promise { }. – Patriks Jul 22 '21 at 20:41
  • It is returning undefined or Promise { } because you are trying to use the value before the toDataURL function is complete. I recommend checking out the link provided in the comment from @David and read about synchronous and asynchronous patterns. – JCH Jul 22 '21 at 20:47
  • Its not a working answer. To make it work You need to ex. async whole code and `await QRCode.toDataURL...` – fosfik Dec 02 '22 at 13:13