Node.js throws “btoa is not defined” error

后端 未结 10 1469
悲&欢浪女
悲&欢浪女 2020-12-02 04:40

In my node.js application I did an npm install btoa-atob so that I could use the btoa() and atob() functions which are native in clien

相关标签:
10条回答
  • 2020-12-02 04:50

    Here's a concise universal solution for base64 encoding:

    const nodeBtoa = (b) => Buffer.from(b).toString('base64');
    export const base64encode = typeof btoa !== 'undefined' ? btoa : nodeBtoa;
    
    0 讨论(0)
  • 2020-12-02 04:53

    Maybe you don't need it anymore but if someone needs this using node: https://www.npmjs.com/package/btoa

    0 讨论(0)
  • 2020-12-02 04:56

    The 'btoa-atob' module does not export a programmatic interface, it only provides command line utilities.

    If you need to convert to Base64 you could do so using Buffer:

    console.log(Buffer.from('Hello World!').toString('base64'));
    

    Reverse (assuming the content you're decoding is a utf8 string):

    console.log(Buffer.from(b64Encoded, 'base64').toString());
    

    Note: prior to Node v4, use new Buffer rather than Buffer.from.

    0 讨论(0)
  • 2020-12-02 05:00

    The solutions posted here don't work in non-ascii characters (i.e. if you plan to exchange base64 between Node.js and a browser). In order to make it work you have to mark the input text as 'binary'.

    Buffer.from('Hélló wórld!!', 'binary').toString('base64')
    

    This gives you SOlsbPMgd/NybGQhIQ==. If you make atob('SOlsbPMgd/NybGQhIQ==') in a browser it will decode it in the right way. It will do it right also in Node.js via:

    Buffer.from('SOlsbPMgd/NybGQhIQ==', 'base64').toString('binary')
    

    If you don't do the "binary part", you will decode wrongly the special chars.

    I got it from the implementation of the btoa npm package:

    0 讨论(0)
提交回复
热议问题