Home > OS >  issue with decoding base64: Decoded string is empty
issue with decoding base64: Decoded string is empty

Time:08-27

I am trying to decode and encode string to base64 using the following code:

export function encode(data: string) {
    console.log('entered encode', data)
    return Buffer.from(data, 'utf-8').toString('base64')
}

export function decode(data:string ){
    console.log('entered decode', data)
    return Buffer.from(data, 'base64').toString('utf-8')
}

now when I try to run encode it works perfectly and returns me a base64 string but when I try to convert it back to utf-8 it gives me a empty string. I've tried doing this using the following code:

const hash = '=ZWYwMjAyY2UtZWFkNy00ZDk4LWFkOTQtODAzZDJiMWM0ZGI5OnRyeUB0cnkuY29t'
const decoded= decode(hash).split(':')
console.log('decoded string', decoded)
console.log(decode(does this work??))

the output of the console after above code executed:

entered decode =ZWYwMjAyY2UtZWFkNy00ZDk4LWFkOTQtODAzZDJiMWM0ZGI5OnRyeUB0cnkuY29t
decoded string [ '' ]
entered decode does this work?
v�����

could someone help me out with what am I doing wrong here?

CodePudding user response:

try remove '=', maybe you wrong while encode

export function decode(data:string ){
        console.log('entered decode', data)
        return Buffer.from(data, 'base64').toString('utf-8')
}

const hash = 'ZWYwMjAyY2UtZWFkNy00ZDk4LWFkOTQtODAzZDJiMWM0ZGI5OnRyeUB0cnkuY29t'
    const decoded= decode(hash).split(':')
    console.log('decoded string', decoded)
    console.log(decode(does this work??))
  • Related