Search code examples
node.jsasynchronousqr-code

How can i assign data as variable in node?


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()

Solution

  • 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
    });