Node.js throws “btoa is not defined” error

后端 未结 10 1602
悲&欢浪女
悲&欢浪女 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:48

    I have a code shared between server and client and I needed an implementation of btoa inside it. I tried doing something like:

    const btoaImplementation =  btoa || (str => Buffer.from(str).toString('base64'));
    

    but the Server would crush with:

    ReferenceError: btoa is not defined

    while Buffer is not defined on the client.

    I couldn't check window.btoa (it's a shared code, remember?)

    So I ended up with this implementation:

    const btoaImplementation = str => {
        try {
            return btoa(str);
        } catch(err) {
            return Buffer.from(str).toString('base64')
        }
    };
    

提交回复
热议问题