From 61b9ed3bf28b4f30c5c53fc65c51d33a9cccfa74 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alfredo=20Gonz=C3=A1lez?= <12631491+mfdebian@users.noreply.github.com> Date: Sat, 28 Sep 2024 12:48:33 -0300 Subject: [PATCH] doc: add esm examples to node:net PR-URL: https://github.com/nodejs/node/pull/55134 Reviewed-By: Luigi Pinca Reviewed-By: Antoine du Hamel Reviewed-By: Benjamin Gruenbaum --- doc/api/net.md | 65 ++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 60 insertions(+), 5 deletions(-) diff --git a/doc/api/net.md b/doc/api/net.md index 7373ce35d583d2..536c9d9d92e248 100644 --- a/doc/api/net.md +++ b/doc/api/net.md @@ -14,7 +14,11 @@ TCP or [IPC][] servers ([`net.createServer()`][]) and clients It can be accessed using: -```js +```mjs +import net from 'node:net'; +``` + +```cjs const net = require('node:net'); ``` @@ -1531,7 +1535,23 @@ Additional options: Following is an example of a client of the echo server described in the [`net.createServer()`][] section: -```js +```mjs +import net from 'node:net'; +const client = net.createConnection({ port: 8124 }, () => { + // 'connect' listener. + console.log('connected to server!'); + client.write('world!\r\n'); +}); +client.on('data', (data) => { + console.log(data.toString()); + client.end(); +}); +client.on('end', () => { + console.log('disconnected from server'); +}); +``` + +```cjs const net = require('node:net'); const client = net.createConnection({ port: 8124 }, () => { // 'connect' listener. @@ -1558,10 +1578,26 @@ option. In this case, the `onread` option will be only used to call `new net.Socket([options])` and the `port` option will be used to call `socket.connect(options[, connectListener])`. -```js +```mjs +import net from 'node:net'; +import { Buffer } from 'node:buffer'; +net.createConnection({ + port: 8124, + onread: { + // Reuses a 4KiB Buffer for every read from the socket. + buffer: Buffer.alloc(4 * 1024), + callback: function(nread, buf) { + // Received data is available in `buf` from 0 to `nread`. + console.log(buf.toString('utf8', 0, nread)); + }, + }, +}); +``` + +```cjs const net = require('node:net'); net.createConnection({ - port: 80, + port: 8124, onread: { // Reuses a 4KiB Buffer for every read from the socket. buffer: Buffer.alloc(4 * 1024), @@ -1684,7 +1720,26 @@ The server can be a TCP server or an [IPC][] server, depending on what it Here is an example of a TCP echo server which listens for connections on port 8124: -```js +```mjs +import net from 'node:net'; +const server = net.createServer((c) => { + // 'connection' listener. + console.log('client connected'); + c.on('end', () => { + console.log('client disconnected'); + }); + c.write('hello\r\n'); + c.pipe(c); +}); +server.on('error', (err) => { + throw err; +}); +server.listen(8124, () => { + console.log('server bound'); +}); +``` + +```cjs const net = require('node:net'); const server = net.createServer((c) => { // 'connection' listener.