# 受信メッセージ

メッセージイベントを処理することによってメッセージが受信されます。形式は以下の通りです：

`function (topic, message, packet) {}`

以下に示すのは例示コードです：

```javascript
//handle incoming messages
client.on('message',function(topic, message, packet){
	console.log("message is "+ message);
	console.log("topic is "+ topic);
	console.log("packet =" +JSON.stringify(packet));
	console.log("packet retain =" +packet.retain);
});
```

メッセージにはテキストメッセージが含まれ、パケットオブジェクトには、以下に示すように、リテインフラグなどのメッセージプロパティに加えて、メッセージがバッファオブジェクトとして含まれています

```javascript
message is {"volts":240}
topic is testtopic
packet ={"cmd":"publish","retain":false,"qos":0,"dup":false,"length":27,"topic":"testtopic","payload":{"type":"Buffer","data":[123,34,118,111,108,116,115,34,58,50,52,48,125]},"properties":{"subscriptionIdentifier":1}}
```

## &#x20;サンプルコード

次のコードは `on.message()` 関数の一部です。

### メッセージが保持されているかを検出する

```javascript
console.log("packet retain =" +packet.retain);
if(packet.retain)
console.log("message is a retained message");
else
console.log("message is not retained message");
```

### メッセージからサブスクリプション識別子を抽出します

```
console.log("subscription Identifier= "+packet.properties.subscriptionIdentifier)
```

### 受信したJSONペイロードで作業する

受信したJSONペイロードを使用するには、まず次を使用してペイロードをJavaScriptオブジェクトに変換する必要があります:

```javascript
let message=JSON.parse(message);
```

受信したメッセージの例です

```javascript
message is {“volts”:240}
```

電圧を得るために、私たちは以下のことを行います

```javascript
let message=JSON.parse(message);
let volts=message.volts;
```

ペイロードがJSONでない可能性があるため、テストする必要があります。以下に示すように、try catchシーケンス（参照）を使用するのが最も簡単な方法です。

```javascript
try
{
message=JSON.parse(message);
let volts=message.volts
console.log("volts="+volts);
}
catch(err)
{
	console.log("not JSON");
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.fubogroup.com/chtoriaru/messji.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
