반응형
https://github.com/protobufjs/protobuf.js/
GitHub - protobufjs/protobuf.js: Protocol Buffers for JavaScript & TypeScript.
Protocol Buffers for JavaScript & TypeScript. Contribute to protobufjs/protobuf.js development by creating an account on GitHub.
github.com
Protocol Buffers란?
Google이 개발한 언어 중립적 데이터 직렬화 형식
- JSON/XML보다 3-10배 빠름
- 더 작은 크기로 데이터 전송
- 성능 중요한 애플리케이션에서 사용
.proto 파일 구조
package ecommerce; // 네임스페이스
message Product {
required string product_id = 1; // 필수: 상품 ID
required string name = 2; // 필수: 상품명
optional string description = 3; // 선택적: 상품 설명
required double price = 4; // 필수: 가격
optional bool is_available = 5; // 선택적: 판매 가능 여부
repeated string categories = 6; // 배열: 카테고리 목록
optional int32 stock_quantity = 7; // 선택적: 재고 수량
repeated string image_urls = 8; // 배열: 이미지 URL 목록
optional int64 created_timestamp = 9; // 선택적: 생성 시간
optional bytes thumbnail = 10; // 선택적: 썸네일 이미지 데이터
repeated string tags = 11; // 배열: 태그 목록
optional float rating = 12; // 선택적: 평점
required string seller_id = 13; // 필수: 판매자 ID
}
필드 타입
required
: 반드시 필요한 필드optional
: 선택적 필드repeated
: 배열/리스트 필드
데이터 타입
string
,int32
,bool
,bytes
등- 각 필드는 고유 번호 필수 (
= 1
,= 2
, ...)
JavaScript 사용법
1. 설치
npm install protobufjs
2. 기본 사용
const protobuf = require("protobufjs");
// .proto 파일 로드
const root = protobuf.loadSync("proto/ecommerce.proto");
const Product = root.lookupType("ecommerce.Product");
// 메시지 생성
const message = Product.create({
product_id: "PROD-12345",
name: "무선 블루투스 이어폰",
description: "고음질 노이즈 캔슬링 기능",
price: 129.99,
is_available: true,
categories: ["전자제품", "오디오", "이어폰"],
stock_quantity: 50,
image_urls: [
"https://example.com/img1.jpg",
"https://example.com/img2.jpg"
],
created_timestamp: Date.now(),
tags: ["블루투스", "노이즈캔슬링", "무선"],
rating: 4.5,
seller_id: "SELLER-789"
});
// 직렬화 (바이너리로 변환)
const buffer = Product.encode(message).finish();
// 역직렬화 (바이너리에서 객체로)
const decoded = Product.decode(buffer);
console.log(decoded.name); // "무선 블루투스 이어폰"
정리
특징 | JSON | Protocol Buffers |
---|---|---|
속도 | 기준 | 3-10배 빠름 |
크기 | 기준 | 더 작음 |
타입 안전성 | 없음 | 있음 |
스키마 진화 | 어려움 | 쉬움 |
참고
Protocol Buffers
Protocol Buffers are language-neutral, platform-neutral extensible mechanisms for serializing structured data.
protobuf.dev
반응형
'개발 아카이브 > Javascript' 카테고리의 다른 글
Uint8Array.from()이 반복문보다 빠른 이유 (1) | 2025.08.02 |
---|---|
TypedArray와 일반 배열과의 성능 차이 정리 (4) | 2025.08.02 |
크롬 AI 번역 API - Translator API (7) | 2025.07.25 |
Google Apps Script에 ChatGPT 연동하기 (3) | 2024.07.24 |
[Sveltekit] 버튼 hover시 +page.server.js 실행을 막는 법 (0) | 2024.06.17 |