{ "type": "module", "source": "doc/api/net.md", "modules": [ { "textRaw": "Net", "name": "net", "introduced_in": "v0.10.0", "desc": "\n
\n\nStability: 2 - Stable
\n
Source Code: lib/net.js
\nThe 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:
\nconst net = require('node:net');\n
",
"modules": [
{
"textRaw": "IPC support",
"name": "ipc_support",
"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 gets truncated to an OS-dependent length of\nsizeof(sockaddr_un.sun_path) - 1
. Typical values are 107 bytes on Linux and\n103 bytes on macOS. If a Node.js API abstraction creates the Unix domain socket,\nit will unlink the Unix domain socket as well. For example,\nnet.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
",
"type": "module",
"displayName": "Identifying paths for IPC connections"
}
],
"type": "module",
"displayName": "IPC support"
}
],
"classes": [
{
"textRaw": "Class: `net.BlockList`",
"type": "class",
"name": "net.BlockList",
"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.addRange(start, end[, type])`", "type": "method", "name": "addRange", "meta": { "added": [ "v15.0.0", "v14.18.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`start` {string|net.SocketAddress} The starting IPv4 or IPv6 address in the range.", "name": "start", "type": "string|net.SocketAddress", "desc": "The starting IPv4 or IPv6 address in the range." }, { "textRaw": "`end` {string|net.SocketAddress} The ending IPv4 or IPv6 address in the range.", "name": "end", "type": "string|net.SocketAddress", "desc": "The ending IPv4 or IPv6 address in the range." }, { "textRaw": "`type` {string} Either `'ipv4'` or `'ipv6'`. **Default:** `'ipv4'`.", "name": "type", "type": "string", "default": "`'ipv4'`", "desc": "Either `'ipv4'` or `'ipv6'`." } ] } ], "desc": "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])`", "type": "method", "name": "check", "meta": { "added": [ "v15.0.0", "v14.18.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "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'`." } ] } ], "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
"
}
],
"properties": [
{
"textRaw": "`rules` Type: {string\\[]}",
"type": "string\\[]",
"name": "Type",
"meta": {
"added": [
"v15.0.0",
"v14.18.0"
],
"changes": []
},
"desc": "The list of rules added to the blocklist.
" } ] }, { "textRaw": "Class: `net.SocketAddress`", "type": "class", "name": "net.SocketAddress", "meta": { "added": [ "v15.14.0", "v14.18.0" ], "changes": [] }, "properties": [ { "textRaw": "`address` Type {string}", "type": "string", "name": "Type", "meta": { "added": [ "v15.14.0", "v14.18.0" ], "changes": [] }, "desc": "Either `'ipv4'` or `'ipv6'`." }, { "textRaw": "`family` Type {string} Either `'ipv4'` or `'ipv6'`.", "type": "string", "name": "Type", "meta": { "added": [ "v15.14.0", "v14.18.0" ], "changes": [] }, "desc": "Either `'ipv4'` or `'ipv6'`." }, { "textRaw": "`flowlabel` Type {number}", "type": "number", "name": "Type", "meta": { "added": [ "v15.14.0", "v14.18.0" ], "changes": [] } }, { "textRaw": "`port` Type {number}", "type": "number", "name": "Type", "meta": { "added": [ "v15.14.0", "v14.18.0" ], "changes": [] } } ], "signatures": [ { "params": [ { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`address` {string} The network address as either an IPv4 or IPv6 string. **Default**: `'127.0.0.1'` if `family` is `'ipv4'`; `'::'` if `family` is `'ipv6'`.", "name": "address", "type": "string", "desc": "The network address as either an IPv4 or IPv6 string. **Default**: `'127.0.0.1'` if `family` is `'ipv4'`; `'::'` if `family` is `'ipv6'`." }, { "textRaw": "`family` {string} One of either `'ipv4'` or `'ipv6'`. **Default**: `'ipv4'`.", "name": "family", "type": "string", "desc": "One of either `'ipv4'` or `'ipv6'`. **Default**: `'ipv4'`." }, { "textRaw": "`flowlabel` {number} An IPv6 flow-label used only if `family` is `'ipv6'`.", "name": "flowlabel", "type": "number", "desc": "An IPv6 flow-label used only if `family` is `'ipv6'`." }, { "textRaw": "`port` {number} An IP port.", "name": "port", "type": "number", "desc": "An IP port." } ] } ] } ] }, { "textRaw": "Class: `net.Server`", "type": "class", "name": "net.Server", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "desc": "This class is used to create a TCP or IPC server.
", "events": [ { "textRaw": "Event: `'close'`", "type": "event", "name": "close", "meta": { "added": [ "v0.5.0" ], "changes": [] }, "params": [], "desc": "Emitted when the server closes. If connections exist, this\nevent is not emitted until all connections are ended.
" }, { "textRaw": "Event: `'connection'`", "type": "event", "name": "connection", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "params": [ { "textRaw": "{net.Socket} The connection object", "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
.
data
<Object> The argument passed to event listener.\n\nReturns 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])`",
"type": "method",
"name": "listen",
"meta": {
"added": [
"v0.5.10"
],
"changes": []
},
"signatures": [
{
"return": {
"textRaw": "Returns: {net.Server}",
"name": "return",
"type": "net.Server"
},
"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"
},
{
"textRaw": "`callback` {Function}",
"name": "callback",
"type": "Function"
}
]
}
],
"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), or an object with an fd
member that is a\nvalid file descriptor.
Listening on a file descriptor is not supported on Windows.
" }, { "textRaw": "`server.listen(options[, callback])`", "type": "method", "name": "listen", "meta": { "added": [ "v0.11.14" ], "changes": [ { "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": [ { "return": { "textRaw": "Returns: {net.Server}", "name": "return", "type": "net.Server" }, "params": [ { "textRaw": "`options` {Object} Required. Supports the following properties:", "name": "options", "type": "Object", "desc": "Required. Supports the following properties:", "options": [ { "textRaw": "`port` {number}", "name": "port", "type": "number" }, { "textRaw": "`host` {string}", "name": "host", "type": "string" }, { "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": "`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": "`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": "`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": "`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": "`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": "`callback` {Function} functions.", "name": "callback", "type": "Function", "desc": "functions." } ] } ], "desc": "If port
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])`",
"type": "method",
"name": "listen",
"meta": {
"added": [
"v0.1.90"
],
"changes": []
},
"signatures": [
{
"return": {
"textRaw": "Returns: {net.Server}",
"name": "return",
"type": "net.Server"
},
"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."
},
{
"textRaw": "`callback` {Function}.",
"name": "callback",
"type": "Function",
"desc": "."
}
]
}
],
"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 unref
ed server will\nnot let the program exit if it's the only server left (the default behavior).\nIf the server is ref
ed 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 unref
ed calling\nunref()
again will have no effect.
Set this property to reject connections when the server's connection count gets\nhigh.
\nIt is not recommended to use this option once a socket has been sent to a child\nwith child_process.fork()
.
net.Server
is an EventEmitter
with the following events:
This 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.
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.
\nerr
<Error> | <null> The error object. See dns.lookup()
.address
<string> The IP address.family
<number> | <null> The address type. See dns.lookup()
.host
<string> The host name.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.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:
port
<number> Required. Port the socket should connect to.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.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.lookup
<Function> Custom lookup function. Default: dns.lookup()
.noDelay
<boolean> If set to true
, it disables the use of Nagle's algorithm immediately\nafter the socket is established. Default: false
.keepAlive
<boolean> If set to true
, it enables keep-alive functionality on the socket\nimmediately after the connection is established, similarly on what is done in\nsocket.setKeepAlive([enable][, initialDelay])
.\nDefault: false
.keepAliveInitialDelay
<number> If set to a positive number, it sets the initial delay before\nthe first keepalive probe is sent on an idle socket.Default: 0
.autoSelectFamily
<boolean>: If set to true
, it enables a family autodetection algorithm\nthat loosely implements section 5 of RFC 8305.\nThe all
option passed to lookup is set to true
and the sockets attempts to connect to all\nobtained IPv6 and IPv4 addresses, in sequence, until a connection is established.\nThe first returned AAAA address is tried first, then the first returned A address,\nthen the second returned AAAA address and so on.\nEach connection attempt (but the last one) is given the amount of time specified by the autoSelectFamilyAttemptTimeout
option before timing out and trying the next address.\nIgnored if the family
option is not 0
or if localAddress
is set.\nConnection errors are not emitted if at least one connection succeeds.\nIf all connections attempts fails, a single AggregateError
with all failed attempts is emitted.\nDefault: net.getDefaultAutoSelectFamily()
autoSelectFamilyAttemptTimeout
<number>: The amount of time in milliseconds to wait\nfor a connection attempt to finish before trying the next address when using the autoSelectFamily
option.\nIf set to a positive integer less than 10
, then the value 10
will be used instead.\nDefault: net.getDefaultAutoSelectFamilyAttemptTimeout()
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.For both types, available options
include:
onread
<Object> If specified, incoming data is stored in a single buffer
\nand passed to the supplied callback
when data arrives on the socket.\nThis will cause the streaming functionality to not provide any data.\nThe socket will emit events like 'error'
, 'end'
, and 'close'
\nas usual. Methods like pause()
and resume()
will also behave as\nexpected.\nbuffer
<Buffer> | <Uint8Array> | <Function> Either a reusable chunk of memory to\nuse for storing incoming data or a function that returns such.callback
<Function> This function is called for every chunk of incoming\ndata. Two arguments are passed to it: the number of bytes written to\nbuffer
and a reference to buffer
. Return false
from this function to\nimplicitly pause()
the socket. This function will be executed in the\nglobal context.Following is an example of a client using the onread
option:
const net = require('node:net');\nnet.connect({\n port: 80,\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": "`socket.connect(path[, connectListener])`",
"type": "method",
"name": "connect",
"signatures": [
{
"return": {
"textRaw": "Returns: {net.Socket} The socket itself.",
"name": "return",
"type": "net.Socket",
"desc": "The socket itself."
},
"params": [
{
"textRaw": "`path` {string} Path the client should connect to. See [Identifying paths for IPC connections][].",
"name": "path",
"type": "string",
"desc": "Path the client should connect to. See [Identifying paths for IPC connections][]."
},
{
"textRaw": "`connectListener` {Function} Common parameter of [`socket.connect()`][] methods. Will be added as a listener for the [`'connect'`][] event once.",
"name": "connectListener",
"type": "Function",
"desc": "Common parameter of [`socket.connect()`][] methods. Will be added as a listener for the [`'connect'`][] event once."
}
]
}
],
"desc": "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 this socket.\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 unref
ed socket will\nnot let the program exit if it's the only socket left (the default behavior).\nIf the socket is ref
ed 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 set the initial\ndelay before the first keepalive probe is sent 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.
Enabling the keep-alive functionality will set the following socket options:
\nSO_KEEPALIVE=1
TCP_KEEPIDLE=initialDelay
TCP_KEEPCNT=10
TCP_KEEPINTVL=1
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.
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 unref
ed 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": "`bytesWritten` {integer}", "type": "integer", "name": "bytesWritten", "meta": { "added": [ "v0.5.3" ], "changes": [] }, "desc": "The amount of bytes sent.
" }, { "textRaw": "`connecting` {boolean}", "type": "boolean", "name": "connecting", "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).
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
.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.
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:
\ntimeout
<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:
const 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
"
},
{
"textRaw": "`net.createConnection(path[, connectListener])`",
"type": "method",
"name": "createConnection",
"meta": {
"added": [
"v0.1.90"
],
"changes": []
},
"signatures": [
{
"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."
},
"params": [
{
"textRaw": "`path` {string} Path the socket should connect to. Will be passed to [`socket.connect(path[, connectListener])`][`socket.connect(path)`]. 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])`][`socket.connect(path)`]. 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])`][`socket.connect(path)`].",
"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])`][`socket.connect(path)`]."
}
]
}
],
"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 packed is received, a FIN packed 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:
\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()`",
"type": "method",
"name": "getDefaultAutoSelectFamily",
"meta": {
"added": [
"v19.4.0"
],
"changes": []
},
"signatures": [
{
"params": []
}
],
"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.
autoSelectFamily
option.Sets the default value of the autoSelectFamily
option of socket.connect(options)
.
value
<boolean> The new default value. The initial default value is false
.Gets the current default value of the autoSelectFamilyAttemptTimeout
option of socket.connect(options)
.\nThe initial default value is 250
.
autoSelectFamilyAttemptTimeout
option.Sets the default value of the autoSelectFamilyAttemptTimeout
option of socket.connect(options)
.
value
<number> The new default value, which must be a positive number. If the number is less than 10
,\nthe value 10
is used instead. The initial default value is 250
.Returns 6
if input
is an IPv6 address. Returns 4
if input
is an IPv4\naddress in dot-decimal notation with no leading zeroes. Otherwise, returns\n0
.
net.isIP('::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)`",
"type": "method",
"name": "isIPv4",
"meta": {
"added": [
"v0.3.0"
],
"changes": []
},
"signatures": [
{
"return": {
"textRaw": "Returns: {boolean}",
"name": "return",
"type": "boolean"
},
"params": [
{
"textRaw": "`input` {string}",
"name": "input",
"type": "string"
}
]
}
],
"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)`",
"type": "method",
"name": "isIPv6",
"meta": {
"added": [
"v0.3.0"
],
"changes": []
},
"signatures": [
{
"return": {
"textRaw": "Returns: {boolean}",
"name": "return",
"type": "boolean"
},
"params": [
{
"textRaw": "`input` {string}",
"name": "input",
"type": "string"
}
]
}
],
"desc": "Returns true
if input
is an IPv6 address. Otherwise, returns false
.
net.isIPv6('::1'); // returns true\nnet.isIPv6('fhqwhgads'); // returns false\n
"
}
],
"type": "module",
"displayName": "Net"
}
]
}