Skip to content

Commit

Permalink
doc: add esm examples to node:net
Browse files Browse the repository at this point in the history
PR-URL: #55134
Reviewed-By: Luigi Pinca <[email protected]>
Reviewed-By: Antoine du Hamel <[email protected]>
Reviewed-By: Benjamin Gruenbaum <[email protected]>
  • Loading branch information
mfdebian authored and targos committed Oct 4, 2024
1 parent 2f59721 commit 4302a48
Showing 1 changed file with 60 additions and 5 deletions.
65 changes: 60 additions & 5 deletions doc/api/net.md
Original file line number Diff line number Diff line change
Expand Up @@ -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');
```

Expand Down Expand Up @@ -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.
Expand All @@ -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),
Expand Down Expand Up @@ -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.
Expand Down

0 comments on commit 4302a48

Please sign in to comment.