{ "type": "module", "source": "doc/api/net.md", "modules": [ { "textRaw": "Net", "name": "net", "introduced_in": "v0.10.0", "type": "module", "stability": 2, "stabilityText": "Stable", "desc": "
The node:net module provides an asynchronous network API for creating stream-based\nTCP or IPC servers (net.createServer()) and clients\n(net.createConnection()).
It can be accessed using:
\nimport net from 'node:net';\n\nconst net = require('node:net');\n",
"modules": [
{
"textRaw": "IPC support",
"name": "ipc_support",
"type": "module",
"meta": {
"changes": [
{
"version": "v20.8.0",
"pr-url": "https://github.com/nodejs/node/pull/49667",
"description": "Support binding to abstract Unix domain socket path like `\\0abstract`. We can bind '\\0' for Node.js `< v20.4.0`."
}
]
},
"desc": "The node:net module supports IPC with named pipes on Windows, and Unix domain\nsockets on other operating systems.
net.connect(), net.createConnection(), server.listen(), and\nsocket.connect() take a path parameter to identify IPC endpoints.
On Unix, the local domain is also known as the Unix domain. The path is a\nfile system pathname. It will throw an error when the length of pathname is\ngreater than the length of sizeof(sockaddr_un.sun_path). Typical values are\n107 bytes on Linux and 103 bytes on macOS. If a Node.js API abstraction creates\nthe Unix domain socket, it will unlink the Unix domain socket as well. For\nexample, net.createServer() may create a Unix domain socket and\nserver.close() will unlink it. But if a user creates the Unix domain\nsocket outside of these abstractions, the user will need to remove it. The same\napplies when a Node.js API creates a Unix domain socket but the program then\ncrashes. In short, a Unix domain socket will be visible in the file system and\nwill persist until unlinked. On Linux, You can use Unix abstract socket by adding\n\\0 to the beginning of the path, such as \\0abstract. The path to the Unix\nabstract socket is not visible in the file system and it will disappear automatically\nwhen all open references to the socket are closed.
On Windows, the local domain is implemented using a named pipe. The path must\nrefer to an entry in \\\\?\\pipe\\ or \\\\.\\pipe\\. Any characters are permitted,\nbut the latter may do some processing of pipe names, such as resolving ..\nsequences. Despite how it might look, the pipe namespace is flat. Pipes will\nnot persist. They are removed when the last reference to them is closed.\nUnlike Unix domain sockets, Windows will close and remove the pipe when the\nowning process exits.
JavaScript string escaping requires paths to be specified with extra backslash\nescaping such as:
\nnet.createServer().listen(\n path.join('\\\\\\\\?\\\\pipe', process.cwd(), 'myctl'));\n",
"displayName": "Identifying paths for IPC connections"
}
],
"displayName": "IPC support"
}
],
"classes": [
{
"textRaw": "Class: `net.BlockList`",
"name": "net.BlockList",
"type": "class",
"meta": {
"added": [
"v15.0.0",
"v14.18.0"
],
"changes": []
},
"desc": "The BlockList object can be used with some network APIs to specify rules for\ndisabling inbound or outbound access to specific IP addresses, IP ranges, or\nIP subnets.
Adds a rule to block the given IP address.
" }, { "textRaw": "`blockList.addAddresses(addresses[, type])`", "name": "addAddresses", "type": "method", "meta": { "added": [ "v26.8.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`addresses` {string[] | net.SocketAddress[]} An array of IPv4 or IPv6 addresses.", "name": "addresses", "type": "string[] | net.SocketAddress[]", "desc": "An array of IPv4 or IPv6 addresses." }, { "textRaw": "`type` {string} Either `'ipv4'` or `'ipv6'`. **Default:** `'ipv4'`.", "name": "type", "type": "string", "default": "`'ipv4'`", "desc": "Either `'ipv4'` or `'ipv6'`.", "optional": true } ] } ], "desc": "Adds multiple address rules to the block list in a single operation.\nThis is more efficient than calling blockList.addAddress() repeatedly\nwhen adding a large number of individual addresses, as the addresses\nare inserted under a single internal lock acquisition.
Adds a subnet rule using CIDR notation. The address family is automatically\ndetected from the address (IPv6 if the address contains ':', IPv4\notherwise). This is equivalent to calling blockList.addSubnet() with\nthe parsed network address, prefix length, and family.
Adds multiple subnet rules using CIDR notation in a single call. The address\nfamily for each entry is automatically detected. This is equivalent to\ncalling blockList.addCIDR() for each element of the array.
Adds a rule to block a range of IP addresses from start (inclusive) to\nend (inclusive).
Adds a rule to block a range of IP addresses specified as a subnet mask.
" }, { "textRaw": "`blockList.check(address[, type])`", "name": "check", "type": "method", "meta": { "added": [ "v15.0.0", "v14.18.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`address` {string | net.SocketAddress} The IP address to check", "name": "address", "type": "string | net.SocketAddress", "desc": "The IP address to check" }, { "textRaw": "`type` {string} Either `'ipv4'` or `'ipv6'`. **Default:** `'ipv4'`.", "name": "type", "type": "string", "default": "`'ipv4'`", "desc": "Either `'ipv4'` or `'ipv6'`.", "optional": true } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "Returns true if the given IP address matches any of the rules added to the\nBlockList.
const blockList = new net.BlockList();\nblockList.addAddress('123.123.123.123');\nblockList.addRange('10.0.0.1', '10.0.0.10');\nblockList.addSubnet('8592:757c:efae:4e45::', 64, 'ipv6');\n\nconsole.log(blockList.check('123.123.123.123')); // Prints: true\nconsole.log(blockList.check('10.0.0.3')); // Prints: true\nconsole.log(blockList.check('222.111.111.222')); // Prints: false\n\n// IPv6 notation for IPv4 addresses works:\nconsole.log(blockList.check('::ffff:7b7b:7b7b', 'ipv6')); // Prints: true\nconsole.log(blockList.check('::ffff:123.123.123.123', 'ipv6')); // Prints: true\n"
},
{
"textRaw": "`blockList.clear()`",
"name": "clear",
"type": "method",
"signatures": [
{
"params": []
}
],
"desc": "\nClears all rules from the BlockList.
const blockList = new net.BlockList();\nconst data = [\n 'Subnet: IPv4 192.168.1.0/24',\n 'Address: IPv4 10.0.0.5',\n 'Range: IPv4 192.168.2.1-192.168.2.10',\n 'Range: IPv4 10.0.0.1-10.0.0.10',\n];\nblockList.fromJSON(data);\nblockList.fromJSON(JSON.stringify(data));\n\nvalue Blocklist.rulesRemoves a rule that was previously added with blockList.addAddress(). The\naddress must match exactly the value used when the rule was added. If the\nspecified address does not exist, this is a no-op.
Removes a subnet rule using CIDR notation. The address family is automatically\ndetected from the address. This is equivalent to calling\nblockList.removeSubnet() with the parsed network address, prefix length,\nand family. If the specified subnet does not exist, this is a no-op.
Removes a rule that was previously added with blockList.addRange(). The start\nand end addresses must match exactly the values used when the rule was added.\nIf the specified range does not exist, this is a no-op.
Removes a rule that was previously added with blockList.addSubnet(). The\nnetwork address and prefix must match exactly the values used when the rule was\nadded. If the specified subnet does not exist, this is a no-op.
A frozen array of CIDR strings representing private, loopback, and link-local\nIP address ranges. This can be passed to blockList.addCIDRs() to quickly\npopulate a blocklist with all non-routable address ranges.
The included ranges are:
\n10.0.0.0/8 â RFC 1918 private IPv4172.16.0.0/12 â RFC 1918 private IPv4192.168.0.0/16 â RFC 1918 private IPv4127.0.0.0/8 â IPv4 loopback::1/128 â IPv6 loopback169.254.0.0/16 â IPv4 link-localfe80::/10 â IPv6 link-localfc00::/7 â IPv6 unique local (ULA)const blockList = new net.BlockList();\nblockList.addCIDRs(net.BlockList.PRIVATE_RANGES);\n\nconsole.log(blockList.check('10.0.0.1')); // Prints: true\nconsole.log(blockList.check('127.0.0.1')); // Prints: true\nconsole.log(blockList.check('8.8.8.8')); // Prints: false\n"
},
{
"textRaw": "Type: {string[]}",
"name": "rules",
"type": "string[]",
"meta": {
"added": [
"v15.0.0",
"v14.18.0"
],
"changes": []
},
"desc": "The list of rules added to the blocklist.
" }, { "textRaw": "Type: {number}", "name": "size", "type": "number", "meta": { "added": [ "v26.8.0" ], "changes": [] }, "desc": "The number of rules in the blocklist. This is equivalent to\nblockList.rules.length but does not allocate the rules array.
EventEmitterThis class is used to create a TCP or IPC server.
\nA listening TCP net.Server can be transferred to a worker thread by listing it\nin the transferList of a worker_threads postMessage() call. This moves\nthe underlying listening socket to the receiving thread, where it resumes\naccepting connections. See Transferring TCP handles to other threads.
net.Server is an EventEmitter with the following events:
Emitted when the server closes. If connections exist, this\nevent is not emitted until all connections are ended.
" }, { "textRaw": "Event: `'connection'`", "name": "connection", "type": "event", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "params": [ { "textRaw": "Type: {net.Socket} The connection object", "name": "type", "type": "net.Socket", "desc": "The connection object" } ], "desc": "Emitted when a new connection is made. socket is an instance of\nnet.Socket.
Emitted when an error occurs. Unlike net.Socket, the 'close'\nevent will not be emitted directly following this event unless\nserver.close() is manually called. See the example in discussion of\nserver.listen().
Emitted when the server has been bound after calling server.listen().
When the number of connections reaches the threshold of server.maxConnections,\nthe server will drop new connections and emit 'drop' event instead. If it is a\nTCP server, the argument is as follows, otherwise the argument is undefined.
Returns the bound address, the address family name, and port of the server\nas reported by the operating system if listening on an IP socket\n(useful to find which port was assigned when getting an OS-assigned address):\n{ port: 12346, family: 'IPv4', address: '127.0.0.1' }.
For a server listening on a pipe or Unix domain socket, the name is returned\nas a string.
\nconst server = net.createServer((socket) => {\n socket.end('goodbye\\n');\n}).on('error', (err) => {\n // Handle errors here.\n throw err;\n});\n\n// Grab an arbitrary unused port.\nserver.listen(() => {\n console.log('opened server on', server.address());\n});\n\nserver.address() returns null before the 'listening' event has been\nemitted or after calling server.close().
Stops the server from accepting new connections and keeps existing\nconnections. This function is asynchronous, the server is finally closed\nwhen all connections are ended and the server emits a 'close' event.\nThe optional callback will be called once the 'close' event occurs. Unlike\nthat event, it will be called with an Error as its only argument if the server\nwas not open when it was closed.
Calls server.close() and returns a promise that fulfills when the\nserver has closed.
Asynchronously get the number of concurrent connections on the server. Works\nwhen sockets were sent to forks.
\nCallback should take two arguments err and count.
Start a server listening for connections. A net.Server can be a TCP or\nan IPC server depending on what it listens to.
Possible signatures:
\nserver.listen(handle[, backlog][, callback])server.listen(options[, callback])server.listen(path[, backlog][, callback])\nfor IPC serversserver.listen([port[, host[, backlog]]][, callback])\nfor TCP serversThis function is asynchronous. When the server starts listening, the\n'listening' event will be emitted. The last parameter callback\nwill be added as a listener for the 'listening' event.
All listen() methods can take a backlog parameter to specify the maximum\nlength of the queue of pending connections. The actual length will be determined\nby the OS through sysctl settings such as tcp_max_syn_backlog and somaxconn\non Linux. The default value of this parameter is 511 (not 512).
All net.Socket are set to SO_REUSEADDR (see socket(7) for\ndetails).
The server.listen() method can be called again if and only if there was an\nerror during the first server.listen() call or server.close() has been\ncalled. Otherwise, an ERR_SERVER_ALREADY_LISTEN error will be thrown.
One of the most common errors raised when listening is EADDRINUSE.\nThis happens when another server is already listening on the requested\nport/path/handle. One way to handle this would be to retry\nafter a certain amount of time:
server.on('error', (e) => {\n if (e.code === 'EADDRINUSE') {\n console.error('Address in use, retrying...');\n setTimeout(() => {\n server.close();\n server.listen(PORT, HOST);\n }, 1000);\n }\n});\n",
"methods": [
{
"textRaw": "`server.listen(handle[, backlog][, callback])`",
"name": "listen",
"type": "method",
"meta": {
"added": [
"v0.5.10"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`handle` {Object}",
"name": "handle",
"type": "Object"
},
{
"textRaw": "`backlog` {number} Common parameter of `server.listen()` functions",
"name": "backlog",
"type": "number",
"desc": "Common parameter of `server.listen()` functions",
"optional": true
},
{
"textRaw": "`callback` {Function}",
"name": "callback",
"type": "Function",
"optional": true
}
],
"return": {
"textRaw": "Returns: {net.Server}",
"name": "return",
"type": "net.Server"
}
}
],
"desc": "Start a server listening for connections on a given handle that has\nalready been bound to a port, a Unix domain socket, or a Windows named pipe.
The handle object can be either a server, a socket (anything with an\nunderlying _handle member), a BoundSocket, or an object with an fd\nmember that is a valid file descriptor.
When handle is a BoundSocket, the server adopts the already-bound\nsocket and starts listening on it. Adoption consumes the bound socket (see\nownership transfer).
Listening on a file descriptor is not supported on Windows.
" }, { "textRaw": "`server.listen(options[, callback])`", "name": "listen", "type": "method", "meta": { "added": [ "v0.11.14" ], "changes": [ { "version": [ "v23.1.0", "v22.12.0" ], "pr-url": "https://github.com/nodejs/node/pull/55408", "description": "The `reusePort` option is supported." }, { "version": "v15.6.0", "pr-url": "https://github.com/nodejs/node/pull/36623", "description": "AbortSignal support was added." }, { "version": "v11.4.0", "pr-url": "https://github.com/nodejs/node/pull/23798", "description": "The `ipv6Only` option is supported." } ] }, "signatures": [ { "params": [ { "textRaw": "`options` {Object} Required. Supports the following properties:", "name": "options", "type": "Object", "desc": "Required. Supports the following properties:", "options": [ { "textRaw": "`backlog` {number} Common parameter of `server.listen()` functions.", "name": "backlog", "type": "number", "desc": "Common parameter of `server.listen()` functions." }, { "textRaw": "`exclusive` {boolean} **Default:** `false`", "name": "exclusive", "type": "boolean", "default": "`false`" }, { "textRaw": "`handle` {net.BoundSocket} A pre-bound `BoundSocket`. The server adopts the already-bound socket and listens on it, ignoring `host`, `port`, and `path`. Adoption consumes the bound socket (see ownership transfer).", "name": "handle", "type": "net.BoundSocket", "desc": "A pre-bound `BoundSocket`. The server adopts the already-bound socket and listens on it, ignoring `host`, `port`, and `path`. Adoption consumes the bound socket (see ownership transfer)." }, { "textRaw": "`host` {string}", "name": "host", "type": "string" }, { "textRaw": "`ipv6Only` {boolean} For TCP servers, setting `ipv6Only` to `true` will disable dual-stack support, i.e., binding to host `::` won't make `0.0.0.0` be bound. **Default:** `false`.", "name": "ipv6Only", "type": "boolean", "default": "`false`", "desc": "For TCP servers, setting `ipv6Only` to `true` will disable dual-stack support, i.e., binding to host `::` won't make `0.0.0.0` be bound." }, { "textRaw": "`reusePort` {boolean} For TCP servers, setting `reusePort` to `true` allows multiple sockets on the same host to bind to the same port. Incoming connections are distributed by the operating system to listening sockets. This option is available only on some platforms, such as Linux 3.9+, DragonFlyBSD 3.6+, FreeBSD 12.0+, Solaris 11.4, and AIX 7.2.5+. On unsupported platforms, this option raises an error. **Default:** `false`.", "name": "reusePort", "type": "boolean", "default": "`false`", "desc": "For TCP servers, setting `reusePort` to `true` allows multiple sockets on the same host to bind to the same port. Incoming connections are distributed by the operating system to listening sockets. This option is available only on some platforms, such as Linux 3.9+, DragonFlyBSD 3.6+, FreeBSD 12.0+, Solaris 11.4, and AIX 7.2.5+. On unsupported platforms, this option raises an error." }, { "textRaw": "`path` {string} Will be ignored if `port` is specified. See Identifying paths for IPC connections.", "name": "path", "type": "string", "desc": "Will be ignored if `port` is specified. See Identifying paths for IPC connections." }, { "textRaw": "`port` {number}", "name": "port", "type": "number" }, { "textRaw": "`readableAll` {boolean} For IPC servers makes the pipe readable for all users. **Default:** `false`.", "name": "readableAll", "type": "boolean", "default": "`false`", "desc": "For IPC servers makes the pipe readable for all users." }, { "textRaw": "`signal` {AbortSignal} An AbortSignal that may be used to close a listening server.", "name": "signal", "type": "AbortSignal", "desc": "An AbortSignal that may be used to close a listening server." }, { "textRaw": "`writableAll` {boolean} For IPC servers makes the pipe writable for all users. **Default:** `false`.", "name": "writableAll", "type": "boolean", "default": "`false`", "desc": "For IPC servers makes the pipe writable for all users." } ] }, { "textRaw": "`callback` {Function} functions.", "name": "callback", "type": "Function", "desc": "functions.", "optional": true } ], "return": { "textRaw": "Returns: {net.Server}", "name": "return", "type": "net.Server" } } ], "desc": "If handle is specified, the server adopts that pre-bound socket. Otherwise, if\nport is specified, it behaves the same as\nserver.listen([port[, host[, backlog]]][, callback]).\nOtherwise, if path is specified, it behaves the same as\nserver.listen(path[, backlog][, callback]).\nIf none of them is specified, an error will be thrown.
If exclusive is false (default), then cluster workers will use the same\nunderlying handle, allowing connection handling duties to be shared. When\nexclusive is true, the handle is not shared, and attempted port sharing\nresults in an error. An example which listens on an exclusive port is\nshown below.
server.listen({\n host: 'localhost',\n port: 80,\n exclusive: true,\n});\n\nWhen exclusive is true and the underlying handle is shared, it is\npossible that several workers query a handle with different backlogs.\nIn this case, the first backlog passed to the master process will be used.
Starting an IPC server as root may cause the server path to be inaccessible for\nunprivileged users. Using readableAll and writableAll will make the server\naccessible for all users.
If the signal option is enabled, calling .abort() on the corresponding\nAbortController is similar to calling .close() on the server:
const controller = new AbortController();\nserver.listen({\n host: 'localhost',\n port: 80,\n signal: controller.signal,\n});\n// Later, when you want to close the server.\ncontroller.abort();\n"
},
{
"textRaw": "`server.listen(path[, backlog][, callback])`",
"name": "listen",
"type": "method",
"meta": {
"added": [
"v0.1.90"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`path` {string} Path the server should listen to. See Identifying paths for IPC connections.",
"name": "path",
"type": "string",
"desc": "Path the server should listen to. See Identifying paths for IPC connections."
},
{
"textRaw": "`backlog` {number} Common parameter of `server.listen()` functions.",
"name": "backlog",
"type": "number",
"desc": "Common parameter of `server.listen()` functions.",
"optional": true
},
{
"textRaw": "`callback` {Function}.",
"name": "callback",
"type": "Function",
"desc": ".",
"optional": true
}
],
"return": {
"textRaw": "Returns: {net.Server}",
"name": "return",
"type": "net.Server"
}
}
],
"desc": "Start an IPC server listening for connections on the given path.
Start a TCP server listening for connections on the given port and host.
If port is omitted or is 0, the operating system will assign an arbitrary\nunused port, which can be retrieved by using server.address().port\nafter the 'listening' event has been emitted.
If host is omitted, the server will accept connections on the\nunspecified IPv6 address (::) when IPv6 is available, or the\nunspecified IPv4 address (0.0.0.0) otherwise.
In most operating systems, listening to the unspecified IPv6 address (::)\nmay cause the net.Server to also listen on the unspecified IPv4 address\n(0.0.0.0).
Opposite of unref(), calling ref() on a previously unrefed server will\nnot let the program exit if it's the only server left (the default behavior).\nIf the server is refed calling ref() again will have no effect.
Calling unref() on a server will allow the program to exit if this is the only\nactive server in the event system. If the server is already unrefed calling\nunref() again will have no effect.
When the number of connections reaches the server.maxConnections threshold:
If the process is not running in cluster mode, Node.js will close the connection.
\nIf the process is running in cluster mode, Node.js will, by default, route the connection to another worker process. To close the connection instead, set server.dropMaxConnection to true.
It is not recommended to use this option once a socket has been sent to a child\nwith child_process.fork().
Set this property to true to begin closing connections once the number of connections reaches the server.maxConnections threshold. This setting is only effective in cluster mode.
stream.DuplexThis class is an abstraction of a TCP socket or a streaming IPC endpoint\n(uses named pipes on Windows, and Unix domain sockets otherwise). It is also\nan EventEmitter.
A net.Socket can be created by the user and used directly to interact with\na server. For example, it is returned by net.createConnection(),\nso the user can use it to talk to the server.
It can also be created by Node.js and passed to the user when a connection\nis received. For example, it is passed to the listeners of a\n'connection' event emitted on a net.Server, so the user can use\nit to interact with the client.
A connected TCP net.Socket can be moved to another thread by listing it in the\ntransferList of a worker_threads postMessage() call. After the\ntransfer, the source socket is destroyed on the sending thread (further use\nfails with ERR_STREAM_DESTROYED rather than silently dropping data), and the\nsocket continues to work on the receiving thread. This makes it possible to\naccept connections on one thread and distribute them across a pool of worker\nthreads, for example to build a node:cluster-like model on top of worker\nthreads.
The socket must be a freshly accepted or created TCP connection: it must still\nbe attached to a live handle, must not be connecting or destroyed, and must not\nhave started reading or have buffered data. Otherwise postMessage() throws\nERR_WORKER_HANDLE_NOT_TRANSFERABLE. Only TCP sockets are supported.
const net = require('node:net');\nconst { Worker } = require('node:worker_threads');\n\n// worker.js receives `{ socket }` messages and handles each connection.\nconst worker = new Worker('./worker.js');\n\nconst server = net.createServer((socket) => {\n // Hand the freshly accepted connection off to the worker thread.\n worker.postMessage({ socket }, [socket]);\n});\nserver.listen(8000);\n\nA listening net.Server can be transferred the same way, which moves the\nlistening socket itself (and its pending accept queue) to the receiving thread.
Creates a new socket object.
\nThe newly created socket can be either a TCP socket or a streaming IPC\nendpoint, depending on what it connect() to.
Emitted once the socket is fully closed. The argument hadError is a boolean\nwhich says if the socket was closed due to a transmission error.
Emitted when a socket connection is successfully established.\nSee net.createConnection().
Emitted when a new connection attempt is started. This may be emitted multiple times\nif the family autoselection algorithm is enabled in socket.connect(options).
Emitted when a connection attempt failed. This may be emitted multiple times\nif the family autoselection algorithm is enabled in socket.connect(options).
Emitted when a connection attempt timed out. This is only emitted (and may be\nemitted multiple times) if the family autoselection algorithm is enabled\nin socket.connect(options).
Emitted when data is received. The argument data will be a Buffer or\nString. Encoding of data is set by socket.setEncoding().
The data will be lost if there is no listener when a Socket\nemits a 'data' event.
Emitted when the write buffer becomes empty. Can be used to throttle uploads.
\nSee also: the return values of socket.write().
Emitted when the other end of the socket signals the end of transmission, thus\nending the readable side of the socket.
\nBy default (allowHalfOpen is false) the socket will send an end of\ntransmission packet back and destroy its file descriptor once it has written out\nits pending write queue. However, if allowHalfOpen is set to true, the\nsocket will not automatically end() its writable side,\nallowing the user to write arbitrary amounts of data. The user must call\nend() explicitly to close the connection (i.e. sending a\nFIN packet back).
Emitted when an error occurs. The 'close' event will be called directly\nfollowing this event.
Emitted after resolving the host name but before connecting.\nNot applicable to Unix sockets.
" }, { "textRaw": "Event: `'ready'`", "name": "ready", "type": "event", "meta": { "added": [ "v9.11.0" ], "changes": [] }, "params": [], "desc": "Emitted when a socket is ready to be used.
\nTriggered immediately after 'connect'.
Emitted if the socket times out from inactivity. This is only to notify that\nthe socket has been idle. The user must manually close the connection.
\nSee also: socket.setTimeout().
Returns the bound address, the address family name and port of the\nsocket as reported by the operating system:\n{ port: 12346, family: 'IPv4', address: '127.0.0.1' }
Initiate a connection on a given socket.
\nPossible signatures:
\nsocket.connect(options[, connectListener])socket.connect(path[, connectListener])\nfor IPC connections.socket.connect(port[, host][, connectListener])\nfor TCP connections.net.Socket The socket itself.This function is asynchronous. When the connection is established, the\n'connect' event will be emitted. If there is a problem connecting,\ninstead of a 'connect' event, an 'error' event will be emitted with\nthe error passed to the 'error' listener.\nThe last parameter connectListener, if supplied, will be added as a listener\nfor the 'connect' event once.
This function should only be used for reconnecting a socket after\n'close' has been emitted or otherwise it may lead to undefined\nbehavior.
Initiate a connection on a given socket. Normally this method is not needed,\nthe socket should be created and opened with net.createConnection(). Use\nthis only when implementing a custom Socket.
For TCP connections, available options are:
autoSelectFamily boolean: If set to true, it enables a family\nautodetection algorithm that loosely implements section 5 of RFC 8305. The\nall option passed to lookup is set to true and the sockets attempts to\nconnect to all obtained IPv6 and IPv4 addresses, in sequence, until a\nconnection is established. The first returned AAAA address is tried first,\nthen the first returned A address, then the second returned AAAA address and\nso on. Each connection attempt (but the last one) is given the amount of time\nspecified by the autoSelectFamilyAttemptTimeout option before timing out and\ntrying the next address. Ignored if the family option is not 0 or if\nlocalAddress is set. Connection errors are not emitted if at least one\nconnection succeeds. If all connections attempts fails, a single\nAggregateError with all failed attempts is emitted. Default:\nnet.getDefaultAutoSelectFamily().autoSelectFamilyAttemptTimeout number: The amount of time in milliseconds\nto wait for a connection attempt to finish before trying the next address when\nusing the autoSelectFamily option. If set to a positive integer less than\n10, then the value 10 will be used instead. Default:\nnet.getDefaultAutoSelectFamilyAttemptTimeout().family number: Version of IP stack. Must be 4, 6, or 0. The value\n0 indicates that both IPv4 and IPv6 addresses are allowed. Default: 0.hints number Optional dns.lookup() hints.host string Host the socket should connect to. Default: 'localhost'.localAddress string Local address the socket should connect from.localPort number Local port the socket should connect from.lookup Function Custom lookup function. Default: dns.lookup().port number Required. Port the socket should connect to.For IPC connections, available options are:
path string Required. Path the client should connect to.\nSee Identifying paths for IPC connections. If provided, the TCP-specific\noptions above are ignored.Initiate an IPC connection on the given socket.
\nAlias to\nsocket.connect(options[, connectListener])\ncalled with { path: path } as options.
Initiate a TCP connection on the given socket.
\nAlias to\nsocket.connect(options[, connectListener])\ncalled with {port: port, host: host} as options.
Ensures that no more I/O activity happens on the current connection.\nDestroys the stream and closes the connection.
\nSee writable.destroy() for further details.
Destroys the socket after all data is written. If the 'finish' event was\nalready emitted the socket is destroyed immediately. If the socket is still\nwritable it implicitly calls socket.end().
Half-closes the socket. i.e., it sends a FIN packet. It is possible the\nserver will still send some data.
\nSee writable.end() for further details.
Pauses the reading of data. That is, 'data' events will not be emitted.\nUseful to throttle back an upload.
Opposite of unref(), calling ref() on a previously unrefed socket will\nnot let the program exit if it's the only socket left (the default behavior).\nIf the socket is refed calling ref again will have no effect.
Close the TCP connection by sending an RST packet and destroy the stream.\nIf this TCP socket is in connecting status, it will send an RST packet and destroy this TCP socket once it is connected.\nOtherwise, it will call socket.destroy with an ERR_SOCKET_CLOSED Error.\nIf this is not a TCP socket (for example, a pipe), calling this method will immediately throw an ERR_INVALID_HANDLE_TYPE Error.
Resumes reading after a call to socket.pause().
Set the encoding for the socket as a Readable Stream. See\nreadable.setEncoding() for more information.
Enable/disable keep-alive functionality, and optionally configure the\nkeepalive probe timing. Returns the socket itself.
\nPossible signatures:
\nsocket.setKeepAlive([options])socket.setKeepAlive([enable][, initialDelay][, interval][, count])Enabling keep-alive sets the initial delay before the first keepalive probe is\nsent on an idle socket.
\nSet initialDelay (in milliseconds) to set the delay between the last\ndata packet received and the first keepalive probe. Setting 0 for\ninitialDelay will leave the value unchanged from the default\n(or previous) setting.
Set interval (in milliseconds) to set the delay between successive\nkeepalive probes once they begin (TCP_KEEPINTVL). Set count to the\nnumber of unacknowledged probes sent before the connection is dropped\n(TCP_KEEPCNT). Both are only applied when keep-alive is enabled.\nOmitting interval or count uses the defaults of 1000 ms and 10.\nAs with initialDelay, a non-positive interval or count leaves the\ncorresponding system default unchanged.
initialDelay and interval are specified in milliseconds but the\nunderlying socket options are configured in whole seconds; the values are\ndivided by 1000 and rounded down before being applied.
Enabling the keep-alive functionality will set the following socket options:
\nSO_KEEPALIVE=1TCP_KEEPIDLE=initialDelay / 1000TCP_KEEPCNT=countTCP_KEEPINTVL=interval / 1000On Windows versions older than build 1709, keep-alive is configured through\nSIO_KEEPALIVE_VALS, which has no probe-count field, so count is ignored on\nthose platforms.
Configure keep-alive using an options object. See socket.setKeepAlive()\nfor a description of each property.
socket.setKeepAlive({ enable: true, initialDelay: 1000, interval: 1000, count: 10 });\n"
},
{
"textRaw": "`socket.setKeepAlive([enable][, initialDelay][, interval][, count])`",
"name": "setKeepAlive",
"type": "method",
"meta": {
"added": [
"v0.1.92"
],
"changes": [
{
"version": "v26.4.0",
"pr-url": "https://github.com/nodejs/node/pull/63825",
"description": "Added the `interval` and `count` arguments to configure `TCP_KEEPINTVL` and `TCP_KEEPCNT`."
},
{
"version": [
"v13.12.0",
"v12.17.0"
],
"pr-url": "https://github.com/nodejs/node/pull/32204",
"description": "New defaults for `TCP_KEEPCNT` and `TCP_KEEPINTVL` socket options were added."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`enable` {boolean} **Default:** `false`",
"name": "enable",
"type": "boolean",
"default": "`false`",
"optional": true
},
{
"textRaw": "`initialDelay` {number} **Default:** `0`",
"name": "initialDelay",
"type": "number",
"default": "`0`",
"optional": true
},
{
"textRaw": "`interval` {number} **Default:** `1000`",
"name": "interval",
"type": "number",
"default": "`1000`",
"optional": true
},
{
"textRaw": "`count` {number} **Default:** `10`",
"name": "count",
"type": "number",
"default": "`10`",
"optional": true
}
],
"return": {
"textRaw": "Returns: {net.Socket} The socket itself.",
"name": "return",
"type": "net.Socket",
"desc": "The socket itself."
}
}
],
"desc": "Configure keep-alive using positional arguments. See\nsocket.setKeepAlive() for a description of each argument.
Enable/disable the use of Nagle's algorithm.
\nWhen a TCP connection is created, it will have Nagle's algorithm enabled.
\nNagle's algorithm delays data before it is sent via the network. It attempts\nto optimize throughput at the expense of latency.
\nPassing true for noDelay or not passing an argument will disable Nagle's\nalgorithm for the socket. Passing false for noDelay will enable Nagle's\nalgorithm.
Sets the socket to timeout after timeout milliseconds of inactivity on\nthe socket. By default net.Socket do not have a timeout.
When an idle timeout is triggered the socket will receive a 'timeout'\nevent but the connection will not be severed. The user must manually call\nsocket.end() or socket.destroy() to end the connection.
socket.setTimeout(3000);\nsocket.on('timeout', () => {\n console.log('socket timeout');\n socket.end();\n});\n\nIf timeout is 0, then the existing idle timeout is disabled.
The optional callback parameter will be added as a one-time listener for the\n'timeout' event.
Returns the current Type of Service (TOS) field for IPv4 packets or Traffic\nClass for IPv6 packets for this socket.
\nsetTypeOfService() may be called before the socket is connected; the value\nwill be cached and applied when the socket establishes a connection.\ngetTypeOfService() will return the currently set value even before connection.
On some platforms (e.g., Linux), certain TOS/ECN bits may be masked or ignored,\nand behavior can differ between IPv4 and IPv6 or dual-stack sockets. Callers\nshould verify platform-specific semantics.
" }, { "textRaw": "`socket.setTypeOfService(tos)`", "name": "setTypeOfService", "type": "method", "meta": { "added": [ "v25.6.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`tos` {integer} The TOS value to set (0-255).", "name": "tos", "type": "integer", "desc": "The TOS value to set (0-255)." } ], "return": { "textRaw": "Returns: {net.Socket} The socket itself.", "name": "return", "type": "net.Socket", "desc": "The socket itself." } } ], "desc": "Sets the Type of Service (TOS) field for IPv4 packets or Traffic Class for IPv6\nPackets sent from this socket. This can be used to prioritize network traffic.
\nsetTypeOfService() may be called before the socket is connected; the value\nwill be cached and applied when the socket establishes a connection.\ngetTypeOfService() will return the currently set value even before connection.
On some platforms (e.g., Linux), certain TOS/ECN bits may be masked or ignored,\nand behavior can differ between IPv4 and IPv6 or dual-stack sockets. Callers\nshould verify platform-specific semantics.
" }, { "textRaw": "`socket.unref()`", "name": "unref", "type": "method", "meta": { "added": [ "v0.9.1" ], "changes": [] }, "signatures": [ { "params": [], "return": { "textRaw": "Returns: {net.Socket} The socket itself.", "name": "return", "type": "net.Socket", "desc": "The socket itself." } } ], "desc": "Calling unref() on a socket will allow the program to exit if this is the only\nactive socket in the event system. If the socket is already unrefed calling\nunref() again will have no effect.
Sends data on the socket. The second parameter specifies the encoding in the\ncase of a string. It defaults to UTF8 encoding.
\nReturns true if the entire data was flushed successfully to the kernel\nbuffer. Returns false if all or part of the data was queued in user memory.\n'drain' will be emitted when the buffer is again free.
The optional callback parameter will be executed when the data is finally\nwritten out, which may not be immediately.
See Writable stream write() method for more\ninformation.
This property is only present if the family autoselection algorithm is enabled in\nsocket.connect(options) and it is an array of the addresses that have been attempted.
Each address is a string in the form of $IP:$PORT. If the connection was successful,\nthen the last address is the one that the socket is currently connected to.
This property shows the number of characters buffered for writing. The buffer\nmay contain strings whose length after encoding is not yet known. So this number\nis only an approximation of the number of bytes in the buffer.
\nnet.Socket has the property that socket.write() always works. This is to\nhelp users get up and running quickly. The computer cannot always keep up\nwith the amount of data that is written to a socket. The network connection\nsimply might be too slow. Node.js will internally queue up the data written to a\nsocket and send it out over the wire when it is possible.
The consequence of this internal buffering is that memory may grow.\nUsers who experience large or growing bufferSize should attempt to\n\"throttle\" the data flows in their program with\nsocket.pause() and socket.resume().
The amount of received bytes.
" }, { "textRaw": "Type: {integer}", "name": "bytesWritten", "type": "integer", "meta": { "added": [ "v0.5.3" ], "changes": [] }, "desc": "The amount of bytes sent.
" }, { "textRaw": "Type: {boolean}", "name": "connecting", "type": "boolean", "meta": { "added": [ "v6.1.0" ], "changes": [] }, "desc": "If true,\nsocket.connect(options[, connectListener]) was\ncalled and has not yet finished. It will stay true until the socket becomes\nconnected, then it is set to false and the 'connect' event is emitted. Note\nthat the\nsocket.connect(options[, connectListener])\ncallback is a listener for the 'connect' event.
See writable.destroyed for further details.
The string representation of the local IP address the remote client is\nconnecting on. For example, in a server listening on '0.0.0.0', if a client\nconnects on '192.168.1.1', the value of socket.localAddress would be\n'192.168.1.1'.
The numeric representation of the local port. For example, 80 or 21.
The string representation of the local IP family. 'IPv4' or 'IPv6'.
This is true if the socket is not connected yet, either because .connect()\nhas not yet been called or because it is still in the process of connecting\n(see socket.connecting).
The string representation of the remote IP address. For example,\n'74.125.127.100' or '2001:4860:a005::68'. Value may be undefined if\nthe socket is destroyed (for example, if the client disconnected).
The string representation of the remote IP family. 'IPv4' or 'IPv6'. Value may be undefined if\nthe socket is destroyed (for example, if the client disconnected).
The numeric representation of the remote port. For example, 80 or 21. Value may be undefined if\nthe socket is destroyed (for example, if the client disconnected).
Reference to the server that accepted the socket. This is null for sockets\nthat were not accepted by a server.
The socket timeout in milliseconds as set by socket.setTimeout().\nIt is undefined if a timeout has not been set.
This property represents the state of the connection as a string.
\nsocket.readyState is opening.open.readOnly.writeOnly.closed.Allows for the synchronous creation of a pre-bound socket, that can be passed\nto listen() or new net.Socket() later on. For listen() this enables\nsynchronous port reservation, while for new net.Socket(), it allows control\nover the local egress port/IP, via bind(2) semantics.
A BoundSocket binds either a TCP endpoint (host or port) or a\nUnix domain/named-pipe endpoint (path); the two are mutually exclusive. For a\npath, the file system entry is reserved in the constructor, so conflicts such\nas EADDRINUSE throw synchronously exactly as a TCP bind does. On Linux a\nleading '\\0' in path selects the abstract namespace (no file system entry);\nan abstract path on any other platform throws ERR_INVALID_ARG_VALUE.
Adoption transfers ownership of the socket; afterwards address() and close()\nthrow ERR_SOCKET_HANDLE_ADOPTED. A handle that is never adopted must be\nclosed to avoid leaking the socket. Closing a pipe BoundSocket removes its\nfile system entry; abstract and TCP binds have none to remove.
When a pipe BoundSocket bound to a source path is adopted as a client, that\npath is reported as the socket's localAddress once it connects.
When an adopted BoundSocket connects to a numeric IP literal, connect(2) is\nissued synchronously, so socket.localAddress is resolved once\nsocket.connect() returns. Connection failures are still reported via a\ndeferred 'error' event.
import net from 'node:net';\n\nconst bound = new net.BoundSocket();\nconst { port } = bound.address();\nconsole.log(`Reserved port ${port} for server`);\n\nconst server = net.createServer();\nserver.listen(bound); // Adopt as a server, or pass to new net.Socket() instead.\n",
"signatures": [
{
"textRaw": "`new net.BoundSocket([options])`",
"name": "net.BoundSocket",
"type": "ctor",
"meta": {
"added": [
"v26.4.0"
],
"changes": [
{
"version": "v26.7.0",
"pr-url": "https://github.com/nodejs/node/pull/64399",
"description": "The `path` option is supported."
}
]
},
"params": [
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`host` {string} Local address to bind. Must be a numeric IP literal; no DNS resolution is performed. **Default:** `'0.0.0.0'`, or `'::'` when `ipv6Only` is `true`.",
"name": "host",
"type": "string",
"default": "`'0.0.0.0'`, or `'::'` when `ipv6Only` is `true`",
"desc": "Local address to bind. Must be a numeric IP literal; no DNS resolution is performed."
},
{
"textRaw": "`port` {number} Local port. `0` requests an OS-assigned ephemeral port. **Default:** `0`.",
"name": "port",
"type": "number",
"default": "`0`",
"desc": "Local port. `0` requests an OS-assigned ephemeral port."
},
{
"textRaw": "`ipv6Only` {boolean} Sets `IPV6_V6ONLY`, disabling dual-stack support so the socket binds IPv6 only. Only meaningful for IPv6 binds. **Default:** `false`.",
"name": "ipv6Only",
"type": "boolean",
"default": "`false`",
"desc": "Sets `IPV6_V6ONLY`, disabling dual-stack support so the socket binds IPv6 only. Only meaningful for IPv6 binds."
},
{
"textRaw": "`reusePort` {boolean} Sets `SO_REUSEPORT`, allowing multiple sockets to bind the same address and port for kernel-level load balancing. Support is platform-dependent. **Default:** `false`.",
"name": "reusePort",
"type": "boolean",
"default": "`false`",
"desc": "Sets `SO_REUSEPORT`, allowing multiple sockets to bind the same address and port for kernel-level load balancing. Support is platform-dependent."
},
{
"textRaw": "`path` {string} Binds a Unix domain socket (or Windows named pipe) at the given path instead of a TCP endpoint. A leading `'\\0'` selects the Linux abstract namespace. Mutually exclusive with `host`, `port`, `ipv6Only`, and `reusePort`; combining them throws `ERR_INVALID_ARG_VALUE`.",
"name": "path",
"type": "string",
"desc": "Binds a Unix domain socket (or Windows named pipe) at the given path instead of a TCP endpoint. A leading `'\\0'` selects the Linux abstract namespace. Mutually exclusive with `host`, `port`, `ipv6Only`, and `reusePort`; combining them throws `ERR_INVALID_ARG_VALUE`."
}
],
"optional": true
}
]
}
],
"methods": [
{
"textRaw": "`boundSocket.address()`",
"name": "address",
"type": "method",
"meta": {
"added": [
"v26.4.0"
],
"changes": [
{
"version": "v26.7.0",
"pr-url": "https://github.com/nodejs/node/pull/64399",
"description": "The bound path is returned for a pipe bind."
}
]
},
"signatures": [
{
"params": [],
"return": {
"textRaw": "Returns: {Object | string} For a TCP bind, an object with `address`, `family`, and `port` properties, as `server.address()` returns. For a pipe bind, the bound path string, as `server.address()` returns for a pipe server.",
"name": "return",
"type": "Object | string",
"desc": "For a TCP bind, an object with `address`, `family`, and `port` properties, as `server.address()` returns. For a pipe bind, the bound path string, as `server.address()` returns for a pipe server."
}
}
],
"desc": "Returns the bound local address. When bound with port: 0, port is the\nOS-assigned ephemeral port.
Returns the file descriptor of the bound socket. Ownership remains with the\nBoundSocket, so the descriptor must not be closed by the caller. The\ndescriptor is only available before the handle is adopted; afterwards it belongs\nto the adopting net.Server or net.Socket and fd() throws\nERR_SOCKET_HANDLE_ADOPTED.
Releases the bound socket. Only needed when the handle is never adopted.
" }, { "textRaw": "`boundSocket[Symbol.dispose]()`", "name": "[Symbol.dispose]", "type": "method", "meta": { "added": [ "v26.4.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "Closes the handle if it has not been adopted or closed; otherwise a no-op.
" } ], "properties": [ { "textRaw": "{boolean}", "name": "isPipe", "type": "boolean", "meta": { "added": [ "v26.7.0" ], "changes": [] }, "desc": "true when the socket was bound with a path (a Unix domain socket or Windows\nnamed pipe), false for a TCP bind. The getter's presence on\nnet.BoundSocket.prototype also serves as a capability probe for path\nsupport.
Aliases to\nnet.createConnection().
Possible signatures:
\nnet.connect(options[, connectListener])net.connect(path[, connectListener]) for IPC\nconnections.net.connect(port[, host][, connectListener])\nfor TCP connections.Alias to\nnet.createConnection(options[, connectListener]).
Alias to\nnet.createConnection(path[, connectListener]).
Alias to\nnet.createConnection(port[, host][, connectListener]).
A factory function, which creates a new net.Socket,\nimmediately initiates connection with socket.connect(),\nthen returns the net.Socket that starts the connection.
When the connection is established, a 'connect' event will be emitted\non the returned socket. The last parameter connectListener, if supplied,\nwill be added as a listener for the 'connect' event once.
Possible signatures:
\nnet.createConnection(options[, connectListener])net.createConnection(path[, connectListener])\nfor IPC connections.net.createConnection(port[, host][, connectListener])\nfor TCP connections.The net.connect() function is an alias to this function.
For available options, see\nnew net.Socket([options])\nand socket.connect(options[, connectListener]).
Additional options:
\nhandle net.BoundSocket A pre-bound BoundSocket used as the\nconnection's source binding, honoring its local address and port. Adoption\nconsumes the bound socket (see ownership transfer).timeout number If set, will be used to call\nsocket.setTimeout(timeout) after the socket is created, but before\nit starts the connection.Following is an example of a client of the echo server described\nin the net.createServer() section:
import net from 'node:net';\nconst client = net.createConnection({ port: 8124 }, () => {\n // 'connect' listener.\n console.log('connected to server!');\n client.write('world!\\r\\n');\n});\nclient.on('data', (data) => {\n console.log(data.toString());\n client.end();\n});\nclient.on('end', () => {\n console.log('disconnected from server');\n});\n\nconst net = require('node:net');\nconst client = net.createConnection({ port: 8124 }, () => {\n // 'connect' listener.\n console.log('connected to server!');\n client.write('world!\\r\\n');\n});\nclient.on('data', (data) => {\n console.log(data.toString());\n client.end();\n});\nclient.on('end', () => {\n console.log('disconnected from server');\n});\n\nTo connect on the socket /tmp/echo.sock:
const client = net.createConnection({ path: '/tmp/echo.sock' });\n\nFollowing is an example of a client using the port and onread\noption. In this case, the onread option will be only used to call\nnew net.Socket([options]) and the port option will be used to\ncall socket.connect(options[, connectListener]).
import net from 'node:net';\nimport { Buffer } from 'node:buffer';\nnet.createConnection({\n port: 8124,\n onread: {\n // Reuses a 4KiB Buffer for every read from the socket.\n buffer: Buffer.alloc(4 * 1024),\n callback: function(nread, buf) {\n // Received data is available in `buf` from 0 to `nread`.\n console.log(buf.toString('utf8', 0, nread));\n },\n },\n});\n\nconst net = require('node:net');\nnet.createConnection({\n port: 8124,\n onread: {\n // Reuses a 4KiB Buffer for every read from the socket.\n buffer: Buffer.alloc(4 * 1024),\n callback: function(nread, buf) {\n // Received data is available in `buf` from 0 to `nread`.\n console.log(buf.toString('utf8', 0, nread));\n },\n },\n});\n"
},
{
"textRaw": "`net.createConnection(path[, connectListener])`",
"name": "createConnection",
"type": "method",
"meta": {
"added": [
"v0.1.90"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`path` {string} Path the socket should connect to. Will be passed to `socket.connect(path[, connectListener])`. See Identifying paths for IPC connections.",
"name": "path",
"type": "string",
"desc": "Path the socket should connect to. Will be passed to `socket.connect(path[, connectListener])`. See Identifying paths for IPC connections."
},
{
"textRaw": "`connectListener` {Function} Common parameter of the `net.createConnection()` functions, an \"once\" listener for the `'connect'` event on the initiating socket. Will be passed to `socket.connect(path[, connectListener])`.",
"name": "connectListener",
"type": "Function",
"desc": "Common parameter of the `net.createConnection()` functions, an \"once\" listener for the `'connect'` event on the initiating socket. Will be passed to `socket.connect(path[, connectListener])`.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {net.Socket} The newly created socket used to start the connection.",
"name": "return",
"type": "net.Socket",
"desc": "The newly created socket used to start the connection."
}
}
],
"desc": "Initiates an IPC connection.
\nThis function creates a new net.Socket with all options set to default,\nimmediately initiates connection with\nsocket.connect(path[, connectListener]),\nthen returns the net.Socket that starts the connection.
Initiates a TCP connection.
\nThis function creates a new net.Socket with all options set to default,\nimmediately initiates connection with\nsocket.connect(port[, host][, connectListener]),\nthen returns the net.Socket that starts the connection.
Creates a new TCP or IPC server.
\nIf allowHalfOpen is set to true, when the other end of the socket\nsignals the end of transmission, the server will only send back the end of\ntransmission when socket.end() is explicitly called. For example, in the\ncontext of TCP, when a FIN packet is received, a FIN packet is sent\nback only when socket.end() is explicitly called. Until then the\nconnection is half-closed (non-readable but still writable). See 'end'\nevent and RFC 1122 (section 4.2.2.13) for more information.
If pauseOnConnect is set to true, then the socket associated with each\nincoming connection will be paused, and no data will be read from its handle.\nThis allows connections to be passed between processes without any data being\nread by the original process. To begin reading data from a paused socket, call\nsocket.resume().
The server can be a TCP server or an IPC server, depending on what it\nlisten() to.
Here is an example of a TCP echo server which listens for connections\non port 8124:
\nimport net from 'node:net';\nconst server = net.createServer((c) => {\n // 'connection' listener.\n console.log('client connected');\n c.on('end', () => {\n console.log('client disconnected');\n });\n c.write('hello\\r\\n');\n c.pipe(c);\n});\nserver.on('error', (err) => {\n throw err;\n});\nserver.listen(8124, () => {\n console.log('server bound');\n});\n\nconst net = require('node:net');\nconst server = net.createServer((c) => {\n // 'connection' listener.\n console.log('client connected');\n c.on('end', () => {\n console.log('client disconnected');\n });\n c.write('hello\\r\\n');\n c.pipe(c);\n});\nserver.on('error', (err) => {\n throw err;\n});\nserver.listen(8124, () => {\n console.log('server bound');\n});\n\nTest this by using telnet:
telnet localhost 8124\n\nTo listen on the socket /tmp/echo.sock:
server.listen('/tmp/echo.sock', () => {\n console.log('server bound');\n});\n\nUse nc to connect to a Unix domain socket server:
nc -U /tmp/echo.sock\n"
},
{
"textRaw": "`net.getDefaultAutoSelectFamily()`",
"name": "getDefaultAutoSelectFamily",
"type": "method",
"meta": {
"added": [
"v19.4.0"
],
"changes": []
},
"signatures": [
{
"params": [],
"return": {
"textRaw": "Returns: {boolean} The current default value of the `autoSelectFamily` option.",
"name": "return",
"type": "boolean",
"desc": "The current default value of the `autoSelectFamily` option."
}
}
],
"desc": "Gets the current default value of the autoSelectFamily option of socket.connect(options).\nThe initial default value is true, unless the command line option\n--no-network-family-autoselection is provided.
Sets the default value of the autoSelectFamily option of socket.connect(options).
Gets the current default value of the autoSelectFamilyAttemptTimeout option of socket.connect(options).\nThe initial default value is 500 or the value specified via the command line\noption --network-family-autoselection-attempt-timeout.
Sets the default value of the autoSelectFamilyAttemptTimeout option of socket.connect(options).
Returns 6 if input is an IPv6 address, including an IPv4-mapped IPv6 address.\nReturns 4 if input is an IPv4 address in dot-decimal notation with no\nleading zeroes. Otherwise, returns 0.
net.isIP('::1'); // returns 6\nnet.isIP('::ffff:127.0.0.1'); // returns 6\nnet.isIP('127.0.0.1'); // returns 4\nnet.isIP('127.000.000.001'); // returns 0\nnet.isIP('127.0.0.1/24'); // returns 0\nnet.isIP('fhqwhgads'); // returns 0\n"
},
{
"textRaw": "`net.isIPv4(input)`",
"name": "isIPv4",
"type": "method",
"meta": {
"added": [
"v0.3.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`input` {string}",
"name": "input",
"type": "string"
}
],
"return": {
"textRaw": "Returns: {boolean}",
"name": "return",
"type": "boolean"
}
}
],
"desc": "Returns true if input is an IPv4 address in dot-decimal notation with no\nleading zeroes. Otherwise, returns false.
net.isIPv4('127.0.0.1'); // returns true\nnet.isIPv4('127.000.000.001'); // returns false\nnet.isIPv4('127.0.0.1/24'); // returns false\nnet.isIPv4('fhqwhgads'); // returns false\n"
},
{
"textRaw": "`net.isIPv6(input)`",
"name": "isIPv6",
"type": "method",
"meta": {
"added": [
"v0.3.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`input` {string}",
"name": "input",
"type": "string"
}
],
"return": {
"textRaw": "Returns: {boolean}",
"name": "return",
"type": "boolean"
}
}
],
"desc": "Returns true if input is an IPv6 address, including an IPv4-mapped IPv6 address.\nOtherwise, returns false.
net.isIPv6('::1'); // returns true\nnet.isIPv6('::ffff:127.0.0.1'); // returns true\nnet.isIPv6('fhqwhgads'); // returns false\n"
}
],
"displayName": "Net"
}
]
}