Computer >> 컴퓨터 >  >> 프로그래밍 >> JavaScript

JavaScript에서 버퍼(Buffer)를 읽을 수 있는 문자열로 변환하는 방법

Node.js 환경의 JavaScript에서 버퍼(Buffer) 객체를 사람이 읽을 수 있는 문자열로 변환하려면 toString('utf8') 메서드를 사용하면 됩니다. 버퍼는 이진 데이터를 담는 객체이기 때문에 그대로 출력하면 내용을 파악하기 어렵지만, UTF-8 인코딩으로 변환하면 원래의 텍스트를 그대로 되찾을 수 있습니다.

버퍼를 문자열로 변환하는 예제 코드

다음 코드에서는 버퍼 객체를 생성한 뒤, 이를 다시 원래 문자열로 복원하는 과정을 단계별로 확인할 수 있습니다.

var actualBufferObject = Buffer.from('[John Smith]', 'utf8')
console.log("The actual buffer object=");
console.log(JSON.stringify(actualBufferObject))
console.log("Get back the original object=");
console.log(actualBufferObject.toString('utf8'));
var myObjectValue = '[John Smith]';
console.log("The data you are getting from the buffer is equal to ASCII code equivalent...")
for (var counter = 0; counter < myObjectValue.length; counter++) {
    console.log("The ascii value of " + myObjectValue[counter] + " is =" + (myObjectValue.charCodeAt(counter)));
}

프로그램 실행 방법

위 프로그램을 실행하려면 아래 명령어를 입력하세요.

node fileName.js

여기서는 파일 이름이 demo197.js라고 가정하겠습니다.

실행 결과

위 코드를 실행하면 다음과 같은 출력 결과를 얻을 수 있습니다.

PS C:\Users\Amit\javascript-code> node demo197.js
The actual buffer object=
{"type":"Buffer","data":[91,74,111,104,110,32,83,109,105,116,104,93]}
Get back the original object=
[John Smith]
The data you are getting from the buffer is equal to ASCII code equivalent...
The ascii value of [ is =91
The ascii value of J is =74
The ascii value of o is =111
The ascii value of h is =104
The ascii value of n is =110
The ascii value of is =32
The ascii value of S is =83
The ascii value of m is =109
The ascii value of i is =105
The ascii value of t is =116
The ascii value of h is =104
The ascii value of ] is =93

결과 해석

JSON.stringify()로 버퍼 객체를 출력하면 {"type":"Buffer","data":[...]} 형태로 표시되며, data 배열 안의 숫자들은 각 문자에 해당하는 바이트 값(ASCII 코드)입니다. 예를 들어 대괄호 '['는 91, 'J'는 74에 해당합니다. 반면 toString('utf8')을 호출하면 이러한 바이트 값들이 다시 '[John Smith]'라는 읽을 수 있는 문자열로 완벽하게 복원되는 것을 확인할 수 있습니다.