2014-04-16 3 views
84

내 node.js 응용 프로그램에서 클라이언트 측 javascript에서 기본 인 btoa() 및 atob() 함수를 사용할 수 있도록 npm install btoa-atob을 수행했지만 어떤 이유로 노드에 포함되지 않았습니다. 새 디렉토리가 내 node_modules 폴더에 나타났습니다.이 폴더는 app.js와 함께 루트에 있습니다. 그런 다음 루트 패키지에있는 package.json 파일에 종속성으로 btoa-atob을 추가해야했습니다.Node.js - "btoa가 정의되지 않았습니다"오류

그러나 어떤 이유로 그것은 여전히 ​​작동하지 않습니다.

console.log(btoa("Hello World!")); 

^정상적으로 출력 콘솔에 "SGVsbG8gV29ybGQh"대신 내가 오류 "btoa은 defiend되지 않습니다."

제대로 설치하지 않았습니까? 나는 무엇을 간과 했는가?

답변

184

'btoa-atob'모듈은 프로그래밍 방식 인터페이스를 내 보내지 않으며 명령 행 유틸리티 만 제공합니다. 당신은 Base64로 변환해야하는 경우

당신은 버퍼 사용하여 그렇게 할 수 있습니다 :

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

역은 (는 디코딩하고있는 내용을 가정하는 UTF8 문자열) :

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

참고 : 노드 v4 이전에는 Buffer.from 대신 new Buffer을 사용하십시오.

+0

감사합니다! – Joey

+17

누군가에게 도움이된다면, 이것을 모카 common.js에 넣어 두었습니다. global.btoa = function (str) {새로운 버퍼 (str) .toString ('base64');};''를 반환하면 내가 브라우저를 가지고있는 것처럼 콘솔에서 테스트 할 수 있습니다. – snapfractalpop

+3

node.js와 브라우저 사이의 또 다른 사소한 차이점은 동형 이성미를 성취하기가 좀 더 어렵게 만듭니다. 대답을 주셔서 감사합니다, @ mscdex, 정말 도움이! (정직하게!) – Swivel

11

React Native와 PouchDB가있는 노드를 사용할 때 팀에서이 문제가 발생했습니다.

$ npm install --save buffer 

확인 Buffer, btoaatob가 전역으로로드 : 여기에 우리가 그것을 해결하는 방법을 ...

NPM 버퍼를 설치하는 것입니다 내가 찾은

global.Buffer = global.Buffer || require('buffer').Buffer; 

if (typeof btoa === 'undefined') { 
    global.btoa = function (str) { 
    return new Buffer(str, 'binary').toString('base64'); 
    }; 
} 

if (typeof atob === 'undefined') { 
    global.atob = function (b64Encoded) { 
    return new Buffer(b64Encoded, 'base64').toString('binary'); 
    }; 
} 
2

이 심하더라도 위의 답변에서 데스크톱 브라우저의 구현이 btoa()atob()과 일치하지 않았습니다.

const btoa = function(str){ return Buffer.from(str).toString('base64'); } 
// returns "4pyT", yet in desktop Chrome would throw an error. 
btoa('✓'); 
// returns "fsO1w6bCvA==", yet in desktop Chrome would return "fvXmvA==" 
btoa(String.fromCharCode.apply(null, new Uint8Array([0x7e, 0xf5, 0xe6, 0xbc]))); 

Buffer 인스턴스는 UTF-8 by default으로 인코딩 된 문자열을 나타내거나 해석합니다. 이 예외가 발생합니다 대조적으로, 데스크탑 크롬, 당신은 심지어 입력 라틴 이외의 문자가 포함 된 문자열, btoa()로 다양합니다 : 따라서 Uncaught DOMException: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.

을 명시 적 latin1encoding type에서 설정해야 당신은 Node.js를하고 브라우저 사이베이스 64를 교환하려는 경우 ASCII 문자가 아닌 문자에서 작동하지 않습니다 여기에 게시

const btoaLatin1 = function(str) { return Buffer.from(str, 'latin1').toString('base64'); } 
const atobLatin1 = function(b64Encoded) {return Buffer.from(b64Encoded, 'base64').toString('latin1');} 

const btoaUTF8 = function(str) { return Buffer.from(str, 'utf8').toString('base64'); } 
const atobUTF8 = function(b64Encoded) {return Buffer.from(b64Encoded, 'base64').toString('utf8');} 

btoaLatin1('✓'); // returns "Ew==" (would be preferable for it to throw error because this is undecodable) 
atobLatin1(btoa('✓')); // returns "\u0019" (END OF MEDIUM) 

btoaUTF8('✓'); // returns "4pyT" 
atobUTF8(btoa('✓')); // returns "✓" 

// returns "fvXmvA==", just like desktop Chrome 
btoaLatin1(String.fromCharCode.apply(null, new Uint8Array([0x7e, 0xf5, 0xe6, 0xbc]))); 
// returns "fsO1w6bCvA==" 
btoaUTF8(String.fromCharCode.apply(null, new Uint8Array([0x7e, 0xf5, 0xe6, 0xbc]))); 
3

용액 : 당신의 Node.js를 심에 대한 순서는 데스크탑 크롬의 인코딩 유형과 일치합니다. 작동 시키려면 입력 텍스트를 'binary'로 표시해야합니다.

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

이렇게하면 SOlsbPMgd/NybGQhIQ==이됩니다. 브라우저에 atob('SOlsbPMgd/NybGQhIQ==')을 만들면 올바른 방법으로 디코딩합니다.당신이 "진 부분을"하지 않으면 당신은 잘못 특수 문자를 디코딩합니다,

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

: 그것은을 통해 Node.js를 마우스 오른쪽 버튼으로도 그것을 할 것입니다.

나는 그것을 from the implementation of the btoa npm package를 가지고 : 일

관련 문제