---
title: Ascoltare da Node.js
project: OpenSync
version: 1.0
section: recipes
language: it
license: MIT
url: https://totaljs.es/docs/it/opensync/1-0/recipes/nodejs-client/
updated: 2026-11-19T09:22:09.965Z
---

# Ascoltare da Node.js

> Un piccolo script Node.js che riceve i messaggi e si riconnette quando la connessione cade.

Node.js 22 e versioni successive hanno un `WebSocket` integrato, quindi questo script non ha bisogno di pacchetti.

## Lo script

Salvalo come `listen.js`, con il tuo indirizzo e il tuo token:

```js
const URL = 'wss://sync.example.com/?token=YOUR_TOKEN&app=Warehouse';

function connect() {
	const ws = new WebSocket(URL);

	ws.onmessage = function(e) {
		const msg = JSON.parse(e.data);
		if (msg.type === 'init') {
			console.log('Connected to', msg.name);
			return;
		}
		console.log(msg.channel, msg.method, JSON.stringify(msg.body));
	};

	ws.onclose = function() {
		console.log('Disconnected, trying again in 3 seconds');
		setTimeout(connect, 3000);
	};
}

connect();
```

## Eseguirlo

```bash
node listen.js
```

Invia un ordine, poi eliminalo:

```bash
curl -X POST -H "Content-Type: application/json" -d '{"id":1002,"status":"paid"}' "https://sync.example.com/sync/orders/"
curl -X DELETE "https://sync.example.com/sync/orders/?id=1002"
```

Lo script stampa, anche attraverso un riavvio di OpenSync:

```text
Connected to Demo sync
orders POST {"id":1002,"status":"paid"}
Disconnected, trying again in 3 seconds
Connected to Demo sync
orders DELETE ""
```

I messaggi inviati mentre lo script era disconnesso non vengono consegnati dopo.

## Inviare dallo stesso script

Per inviare un messaggio agli altri client, chiama `send` sulla connessione aperta:

```js
ws.send(JSON.stringify({ type: 'notify', channel: 'chat', body: { text: 'Hello' } }));
```

Leggi [WebSocket](../../reference/websocket/).
