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

# Escucha desde Node.js

> Un pequeño script de Node.js que recibe los mensajes y se vuelve a conectar cuando se corta la conexión.

Node.js 22 y posteriores tienen `WebSocket` integrado, así que este script no necesita paquetes.

## El script

Guárdalo como `listen.js`, con tu dirección y tu 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();
```

## Ejecútalo

```bash
node listen.js
```

Envía un pedido y luego bórralo:

```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"
```

El script muestra esto, también si OpenSync se reinicia entretanto:

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

Los mensajes enviados mientras el script estaba desconectado no se entregan después.

## Envía desde el mismo script

Para enviar un mensaje a los demás clientes, llama a `send` en la conexión abierta:

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

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