doc: add esm examples to node:net

PR-URL: https://github.com/nodejs/node/pull/55134
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com>
This commit is contained in:
Alfredo González 2024-09-28 12:48:33 -03:00 committed by GitHub
parent 3800d60c66
commit e6427e1d87
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -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.