X Tutup
{ "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()).

\n

It can be accessed using:

\n
import net from 'node:net';\n
\n
const 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.

", "modules": [ { "textRaw": "Identifying paths for IPC connections", "name": "identifying_paths_for_ipc_connections", "type": "module", "desc": "

net.connect(), net.createConnection(), server.listen(), and\nsocket.connect() take a path parameter to identify IPC endpoints.

\n

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.

\n

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.

\n

JavaScript string escaping requires paths to be specified with extra backslash\nescaping such as:

\n
net.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.

", "methods": [ { "textRaw": "`blockList.addAddress(address[, type])`", "name": "addAddress", "type": "method", "meta": { "added": [ "v15.0.0", "v14.18.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`address` {string|net.SocketAddress} An IPv4 or IPv6 address.", "name": "address", "type": "string|net.SocketAddress", "desc": "An IPv4 or IPv6 address." }, { "textRaw": "`type` {string} Either `'ipv4'` or `'ipv6'`. **Default:** `'ipv4'`.", "name": "type", "type": "string", "default": "`'ipv4'`", "desc": "Either `'ipv4'` or `'ipv6'`.", "optional": true } ] } ], "desc": "

Adds a rule to block the given IP address.

" }, { "textRaw": "`blockList.addRange(start, end[, type])`", "name": "addRange", "type": "method", "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'`.", "optional": true } ] } ], "desc": "

Adds a rule to block a range of IP addresses from start (inclusive) to\nend (inclusive).

" }, { "textRaw": "`blockList.addSubnet(net, prefix[, type])`", "name": "addSubnet", "type": "method", "meta": { "added": [ "v15.0.0", "v14.18.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`net` {string|net.SocketAddress} The network IPv4 or IPv6 address.", "name": "net", "type": "string|net.SocketAddress", "desc": "The network IPv4 or IPv6 address." }, { "textRaw": "`prefix` {number} The number of CIDR prefix bits. For IPv4, this must be a value between `0` and `32`. For IPv6, this must be between `0` and `128`.", "name": "prefix", "type": "number", "desc": "The number of CIDR prefix bits. For IPv4, this must be a value between `0` and `32`. For IPv6, this must be between `0` and `128`." }, { "textRaw": "`type` {string} Either `'ipv4'` or `'ipv6'`. **Default:** `'ipv4'`.", "name": "type", "type": "string", "default": "`'ipv4'`", "desc": "Either `'ipv4'` or `'ipv6'`.", "optional": true } ] } ], "desc": "

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.

\n
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.isBlockList(value)`", "name": "isBlockList", "type": "method", "meta": { "added": [ "v23.4.0", "v22.13.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`value` {any} Any JS value", "name": "value", "type": "any", "desc": "Any JS value" } ], "return": { "textRaw": "Returns `true` if the `value` is a `net.BlockList`.", "name": "return", "desc": "`true` if the `value` is a `net.BlockList`." } } ] }, { "textRaw": "`blockList.fromJSON(value)`", "name": "fromJSON", "type": "method", "stability": 1, "stabilityText": "Experimental", "signatures": [ { "params": [ { "name": "value" } ] } ], "desc": " \n
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
\n" }, { "textRaw": "`blockList.toJSON()`", "name": "toJSON", "type": "method", "stability": 1, "stabilityText": "Experimental", "signatures": [ { "params": [], "return": { "textRaw": "Returns Blocklist.rules", "name": "return", "desc": "Blocklist.rules" } } ], "desc": " " } ], "properties": [ { "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": "Class: `net.SocketAddress`", "name": "net.SocketAddress", "type": "class", "meta": { "added": [ "v15.14.0", "v14.18.0" ], "changes": [] }, "signatures": [ { "textRaw": "`new net.SocketAddress([options])`", "name": "net.SocketAddress", "type": "ctor", "meta": { "added": [ "v15.14.0", "v14.18.0" ], "changes": [] }, "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." } ], "optional": true } ] } ], "properties": [ { "textRaw": "Type: {string}", "name": "address", "type": "string", "meta": { "added": [ "v15.14.0", "v14.18.0" ], "changes": [] } }, { "textRaw": "Type: {string} Either `'ipv4'` or `'ipv6'`.", "name": "family", "type": "string", "meta": { "added": [ "v15.14.0", "v14.18.0" ], "changes": [] }, "desc": "Either `'ipv4'` or `'ipv6'`." }, { "textRaw": "Type: {number}", "name": "flowlabel", "type": "number", "meta": { "added": [ "v15.14.0", "v14.18.0" ], "changes": [] } }, { "textRaw": "Type: {number}", "name": "port", "type": "number", "meta": { "added": [ "v15.14.0", "v14.18.0" ], "changes": [] } } ], "methods": [ { "textRaw": "`SocketAddress.parse(input)`", "name": "parse", "type": "method", "meta": { "added": [ "v23.4.0", "v22.13.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`input` {string} An input string containing an IP address and optional port, e.g. `123.1.2.3:1234` or `[1::1]:1234`.", "name": "input", "type": "string", "desc": "An input string containing an IP address and optional port, e.g. `123.1.2.3:1234` or `[1::1]:1234`." } ], "return": { "textRaw": "Returns: {net.SocketAddress} Returns a `SocketAddress` if parsing was successful. Otherwise returns `undefined`.", "name": "return", "type": "net.SocketAddress", "desc": "Returns a `SocketAddress` if parsing was successful. Otherwise returns `undefined`." } } ] } ] }, { "textRaw": "Class: `net.Server`", "name": "net.Server", "type": "class", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "desc": "\n

This class is used to create a TCP or IPC server.

", "signatures": [ { "textRaw": "`new net.Server([options][, connectionListener])`", "name": "net.Server", "type": "ctor", "params": [ { "textRaw": "`options` {Object} See `net.createServer([options][, connectionListener])`.", "name": "options", "type": "Object", "desc": "See `net.createServer([options][, connectionListener])`.", "optional": true }, { "textRaw": "`connectionListener` {Function} Automatically set as a listener for the `'connection'` event.", "name": "connectionListener", "type": "Function", "desc": "Automatically set as a listener for the `'connection'` event.", "optional": true } ], "return": { "textRaw": "Returns: {net.Server}", "name": "return", "type": "net.Server" }, "desc": "

net.Server is an EventEmitter with the following events:

" } ], "events": [ { "textRaw": "Event: `'close'`", "name": "close", "type": "event", "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'`", "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.

" }, { "textRaw": "Event: `'error'`", "name": "error", "type": "event", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "params": [ { "textRaw": "Type: {Error}", "name": "type", "type": "Error" } ], "desc": "

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().

" }, { "textRaw": "Event: `'listening'`", "name": "listening", "type": "event", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "params": [], "desc": "

Emitted when the server has been bound after calling server.listen().

" }, { "textRaw": "Event: `'drop'`", "name": "drop", "type": "event", "meta": { "added": [ "v18.6.0", "v16.17.0" ], "changes": [] }, "params": [ { "textRaw": "`data` {Object} The argument passed to event listener.", "name": "data", "type": "Object", "desc": "The argument passed to event listener.", "options": [ { "textRaw": "`localAddress` {string} Local address.", "name": "localAddress", "type": "string", "desc": "Local address." }, { "textRaw": "`localPort` {number} Local port.", "name": "localPort", "type": "number", "desc": "Local port." }, { "textRaw": "`localFamily` {string} Local family.", "name": "localFamily", "type": "string", "desc": "Local family." }, { "textRaw": "`remoteAddress` {string} Remote address.", "name": "remoteAddress", "type": "string", "desc": "Remote address." }, { "textRaw": "`remotePort` {number} Remote port.", "name": "remotePort", "type": "number", "desc": "Remote port." }, { "textRaw": "`remoteFamily` {string} Remote IP family. `'IPv4'` or `'IPv6'`.", "name": "remoteFamily", "type": "string", "desc": "Remote IP family. `'IPv4'` or `'IPv6'`." } ] } ], "desc": "

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.

" } ], "methods": [ { "textRaw": "`server.address()`", "name": "address", "type": "method", "meta": { "added": [ "v0.1.90" ], "changes": [ { "version": "v18.4.0", "pr-url": "https://github.com/nodejs/node/pull/43054", "description": "The `family` property now returns a string instead of a number." }, { "version": "v18.0.0", "pr-url": "https://github.com/nodejs/node/pull/41431", "description": "The `family` property now returns a number instead of a string." } ] }, "signatures": [ { "params": [], "return": { "textRaw": "Returns: {Object|string|null}", "name": "return", "type": "Object|string|null" } } ], "desc": "

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' }.

\n

For a server listening on a pipe or Unix domain socket, the name is returned\nas a string.

\n
const 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
\n

server.address() returns null before the 'listening' event has been\nemitted or after calling server.close().

" }, { "textRaw": "`server.close([callback])`", "name": "close", "type": "method", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`callback` {Function} Called when the server is closed.", "name": "callback", "type": "Function", "desc": "Called when the server is closed.", "optional": true } ], "return": { "textRaw": "Returns: {net.Server}", "name": "return", "type": "net.Server" } } ], "desc": "

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.

" }, { "textRaw": "`server[Symbol.asyncDispose]()`", "name": "[Symbol.asyncDispose]", "type": "method", "meta": { "added": [ "v20.5.0", "v18.18.0" ], "changes": [ { "version": "v24.2.0", "pr-url": "https://github.com/nodejs/node/pull/58467", "description": "No longer experimental." } ] }, "signatures": [ { "params": [] } ], "desc": "

Calls server.close() and returns a promise that fulfills when the\nserver has closed.

" }, { "textRaw": "`server.getConnections(callback)`", "name": "getConnections", "type": "method", "meta": { "added": [ "v0.9.7" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ], "return": { "textRaw": "Returns: {net.Server}", "name": "return", "type": "net.Server" } } ], "desc": "

Asynchronously get the number of concurrent connections on the server. Works\nwhen sockets were sent to forks.

\n

Callback should take two arguments err and count.

" }, { "textRaw": "`server.listen()`", "name": "listen", "type": "method", "signatures": [ { "params": [] } ], "desc": "

Start a server listening for connections. A net.Server can be a TCP or\nan IPC server depending on what it listens to.

\n

Possible signatures:

\n\n

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

\n

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

\n

All net.Socket are set to SO_REUSEADDR (see socket(7) for\ndetails).

\n

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.

\n

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:

\n
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.

\n

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.

\n

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": "`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 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.

\n

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.

\n
server.listen({\n  host: 'localhost',\n  port: 80,\n  exclusive: true,\n});\n
\n

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

\n

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.

\n

If the signal option is enabled, calling .abort() on the corresponding\nAbortController is similar to calling .close() on the server:

\n
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.

" }, { "textRaw": "`server.listen([port[, host[, backlog]]][, callback])`", "name": "listen", "type": "method", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`port` {number}", "name": "port", "type": "number", "optional": true }, { "textRaw": "`host` {string}", "name": "host", "type": "string", "optional": true }, { "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 a TCP server listening for connections on the given port and host.

\n

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.

\n

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.

\n

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

" } ] }, { "textRaw": "`server.ref()`", "name": "ref", "type": "method", "meta": { "added": [ "v0.9.1" ], "changes": [] }, "signatures": [ { "params": [], "return": { "textRaw": "Returns: {net.Server}", "name": "return", "type": "net.Server" } } ], "desc": "

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.

" }, { "textRaw": "`server.unref()`", "name": "unref", "type": "method", "meta": { "added": [ "v0.9.1" ], "changes": [] }, "signatures": [ { "params": [], "return": { "textRaw": "Returns: {net.Server}", "name": "return", "type": "net.Server" } } ], "desc": "

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.

" } ], "properties": [ { "textRaw": "Type: {boolean} Indicates whether or not the server is listening for connections.", "name": "listening", "type": "boolean", "meta": { "added": [ "v5.7.0" ], "changes": [] }, "desc": "Indicates whether or not the server is listening for connections." }, { "textRaw": "Type: {integer}", "name": "maxConnections", "type": "integer", "meta": { "added": [ "v0.2.0" ], "changes": [ { "version": "v21.0.0", "pr-url": "https://github.com/nodejs/node/pull/48276", "description": "Setting `maxConnections` to `0` drops all the incoming connections. Previously, it was interpreted as `Infinity`." } ] }, "desc": "

When the number of connections reaches the server.maxConnections threshold:

\n
    \n
  1. \n

    If the process is not running in cluster mode, Node.js will close the connection.

    \n
  2. \n
  3. \n

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

    \n
  4. \n
\n

It is not recommended to use this option once a socket has been sent to a child\nwith child_process.fork().

" }, { "textRaw": "Type: {boolean}", "name": "dropMaxConnection", "type": "boolean", "meta": { "added": [ "v23.1.0", "v22.12.0" ], "changes": [] }, "desc": "

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.

" } ] }, { "textRaw": "Class: `net.Socket`", "name": "net.Socket", "type": "class", "meta": { "added": [ "v0.3.4" ], "changes": [] }, "desc": "\n

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.

\n

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.

\n

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.

", "signatures": [ { "textRaw": "`new net.Socket([options])`", "name": "net.Socket", "type": "ctor", "meta": { "added": [ "v0.3.4" ], "changes": [ { "version": "v25.6.0", "pr-url": "https://github.com/nodejs/node/pull/61503", "description": "Added `typeOfService` option." }, { "version": "v15.14.0", "pr-url": "https://github.com/nodejs/node/pull/37735", "description": "AbortSignal support was added." }, { "version": "v12.10.0", "pr-url": "https://github.com/nodejs/node/pull/25436", "description": "Added `onread` option." } ] }, "params": [ { "textRaw": "`options` {Object} Available options are:", "name": "options", "type": "Object", "desc": "Available options are:", "options": [ { "textRaw": "`allowHalfOpen` {boolean} If set to `false`, then the socket will automatically end the writable side when the readable side ends. See `net.createServer()` and the `'end'` event for details. **Default:** `false`.", "name": "allowHalfOpen", "type": "boolean", "default": "`false`", "desc": "If set to `false`, then the socket will automatically end the writable side when the readable side ends. See `net.createServer()` and the `'end'` event for details." }, { "textRaw": "`blockList` {net.BlockList} `blockList` can be used for disabling outbound access to specific IP addresses, IP ranges, or IP subnets.", "name": "blockList", "type": "net.BlockList", "desc": "`blockList` can be used for disabling outbound access to specific IP addresses, IP ranges, or IP subnets." }, { "textRaw": "`fd` {number} If specified, wrap around an existing socket with the given file descriptor, otherwise a new socket will be created.", "name": "fd", "type": "number", "desc": "If specified, wrap around an existing socket with the given file descriptor, otherwise a new socket will be created." }, { "textRaw": "`keepAlive` {boolean} If set to `true`, it enables keep-alive functionality on the socket immediately after the connection is established, similarly on what is done in `socket.setKeepAlive()`. **Default:** `false`.", "name": "keepAlive", "type": "boolean", "default": "`false`", "desc": "If set to `true`, it enables keep-alive functionality on the socket immediately after the connection is established, similarly on what is done in `socket.setKeepAlive()`." }, { "textRaw": "`keepAliveInitialDelay` {number} If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket. **Default:** `0`.", "name": "keepAliveInitialDelay", "type": "number", "default": "`0`", "desc": "If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket." }, { "textRaw": "`noDelay` {boolean} If set to `true`, it disables the use of Nagle's algorithm immediately after the socket is established. **Default:** `false`.", "name": "noDelay", "type": "boolean", "default": "`false`", "desc": "If set to `true`, it disables the use of Nagle's algorithm immediately after the socket is established." }, { "textRaw": "`onread` {Object} If specified, incoming data is stored in a single `buffer` and passed to the supplied `callback` when data arrives on the socket. This will cause the streaming functionality to not provide any data. The socket will emit events like `'error'`, `'end'`, and `'close'` as usual. Methods like `pause()` and `resume()` will also behave as expected.", "name": "onread", "type": "Object", "desc": "If specified, incoming data is stored in a single `buffer` and passed to the supplied `callback` when data arrives on the socket. This will cause the streaming functionality to not provide any data. The socket will emit events like `'error'`, `'end'`, and `'close'` as usual. Methods like `pause()` and `resume()` will also behave as expected.", "options": [ { "textRaw": "`buffer` {Buffer|Uint8Array|Function} Either a reusable chunk of memory to use for storing incoming data or a function that returns such.", "name": "buffer", "type": "Buffer|Uint8Array|Function", "desc": "Either a reusable chunk of memory to use for storing incoming data or a function that returns such." }, { "textRaw": "`callback` {Function} This function is called for every chunk of incoming data. Two arguments are passed to it: the number of bytes written to `buffer` and a reference to `buffer`. Return `false` from this function to implicitly `pause()` the socket. This function will be executed in the global context.", "name": "callback", "type": "Function", "desc": "This function is called for every chunk of incoming data. Two arguments are passed to it: the number of bytes written to `buffer` and a reference to `buffer`. Return `false` from this function to implicitly `pause()` the socket. This function will be executed in the global context." } ] }, { "textRaw": "`readable` {boolean} Allow reads on the socket when an `fd` is passed, otherwise ignored. **Default:** `false`.", "name": "readable", "type": "boolean", "default": "`false`", "desc": "Allow reads on the socket when an `fd` is passed, otherwise ignored." }, { "textRaw": "`signal` {AbortSignal} An Abort signal that may be used to destroy the socket.", "name": "signal", "type": "AbortSignal", "desc": "An Abort signal that may be used to destroy the socket." }, { "textRaw": "`typeOfService` {number} The initial Type of Service (TOS) value.", "name": "typeOfService", "type": "number", "desc": "The initial Type of Service (TOS) value." }, { "textRaw": "`writable` {boolean} Allow writes on the socket when an `fd` is passed, otherwise ignored. **Default:** `false`.", "name": "writable", "type": "boolean", "default": "`false`", "desc": "Allow writes on the socket when an `fd` is passed, otherwise ignored." } ], "optional": true } ], "return": { "textRaw": "Returns: {net.Socket}", "name": "return", "type": "net.Socket" }, "desc": "

Creates a new socket object.

\n

The newly created socket can be either a TCP socket or a streaming IPC\nendpoint, depending on what it connect() to.

" } ], "events": [ { "textRaw": "Event: `'close'`", "name": "close", "type": "event", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "params": [ { "textRaw": "`hadError` {boolean} `true` if the socket had a transmission error.", "name": "hadError", "type": "boolean", "desc": "`true` if the socket had a transmission error." } ], "desc": "

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.

" }, { "textRaw": "Event: `'connect'`", "name": "connect", "type": "event", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "params": [], "desc": "

Emitted when a socket connection is successfully established.\nSee net.createConnection().

" }, { "textRaw": "Event: `'connectionAttempt'`", "name": "connectionAttempt", "type": "event", "meta": { "added": [ "v21.6.0", "v20.12.0" ], "changes": [] }, "params": [ { "textRaw": "`ip` {string} The IP which the socket is attempting to connect to.", "name": "ip", "type": "string", "desc": "The IP which the socket is attempting to connect to." }, { "textRaw": "`port` {number} The port which the socket is attempting to connect to.", "name": "port", "type": "number", "desc": "The port which the socket is attempting to connect to." }, { "textRaw": "`family` {number} The family of the IP. It can be `6` for IPv6 or `4` for IPv4.", "name": "family", "type": "number", "desc": "The family of the IP. It can be `6` for IPv6 or `4` for IPv4." } ], "desc": "

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

" }, { "textRaw": "Event: `'connectionAttemptFailed'`", "name": "connectionAttemptFailed", "type": "event", "meta": { "added": [ "v21.6.0", "v20.12.0" ], "changes": [] }, "params": [ { "textRaw": "`ip` {string} The IP which the socket attempted to connect to.", "name": "ip", "type": "string", "desc": "The IP which the socket attempted to connect to." }, { "textRaw": "`port` {number} The port which the socket attempted to connect to.", "name": "port", "type": "number", "desc": "The port which the socket attempted to connect to." }, { "textRaw": "`family` {number} The family of the IP. It can be `6` for IPv6 or `4` for IPv4.", "name": "family", "type": "number", "desc": "The family of the IP. It can be `6` for IPv6 or `4` for IPv4." }, { "textRaw": "`error` {Error} The error associated with the failure.", "name": "error", "type": "Error", "desc": "The error associated with the failure." } ], "desc": "

Emitted when a connection attempt failed. This may be emitted multiple times\nif the family autoselection algorithm is enabled in socket.connect(options).

" }, { "textRaw": "Event: `'connectionAttemptTimeout'`", "name": "connectionAttemptTimeout", "type": "event", "meta": { "added": [ "v21.6.0", "v20.12.0" ], "changes": [] }, "params": [ { "textRaw": "`ip` {string} The IP which the socket attempted to connect to.", "name": "ip", "type": "string", "desc": "The IP which the socket attempted to connect to." }, { "textRaw": "`port` {number} The port which the socket attempted to connect to.", "name": "port", "type": "number", "desc": "The port which the socket attempted to connect to." }, { "textRaw": "`family` {number} The family of the IP. It can be `6` for IPv6 or `4` for IPv4.", "name": "family", "type": "number", "desc": "The family of the IP. It can be `6` for IPv6 or `4` for IPv4." } ], "desc": "

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

" }, { "textRaw": "Event: `'data'`", "name": "data", "type": "event", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "params": [ { "textRaw": "Type: {Buffer|string}", "name": "type", "type": "Buffer|string" } ], "desc": "

Emitted when data is received. The argument data will be a Buffer or\nString. Encoding of data is set by socket.setEncoding().

\n

The data will be lost if there is no listener when a Socket\nemits a 'data' event.

" }, { "textRaw": "Event: `'drain'`", "name": "drain", "type": "event", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "params": [], "desc": "

Emitted when the write buffer becomes empty. Can be used to throttle uploads.

\n

See also: the return values of socket.write().

" }, { "textRaw": "Event: `'end'`", "name": "end", "type": "event", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "params": [], "desc": "

Emitted when the other end of the socket signals the end of transmission, thus\nending the readable side of the socket.

\n

By 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).

" }, { "textRaw": "Event: `'error'`", "name": "error", "type": "event", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "params": [ { "textRaw": "Type: {Error}", "name": "type", "type": "Error" } ], "desc": "

Emitted when an error occurs. The 'close' event will be called directly\nfollowing this event.

" }, { "textRaw": "Event: `'lookup'`", "name": "lookup", "type": "event", "meta": { "added": [ "v0.11.3" ], "changes": [ { "version": "v5.10.0", "pr-url": "https://github.com/nodejs/node/pull/5598", "description": "The `host` parameter is supported now." } ] }, "params": [ { "textRaw": "`err` {Error|null} The error object. See `dns.lookup()`.", "name": "err", "type": "Error|null", "desc": "The error object. See `dns.lookup()`." }, { "textRaw": "`address` {string} The IP address.", "name": "address", "type": "string", "desc": "The IP address." }, { "textRaw": "`family` {number|null} The address type. See `dns.lookup()`.", "name": "family", "type": "number|null", "desc": "The address type. See `dns.lookup()`." }, { "textRaw": "`host` {string} The host name.", "name": "host", "type": "string", "desc": "The host name." } ], "desc": "

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.

\n

Triggered immediately after 'connect'.

" }, { "textRaw": "Event: `'timeout'`", "name": "timeout", "type": "event", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "params": [], "desc": "

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.

\n

See also: socket.setTimeout().

" } ], "methods": [ { "textRaw": "`socket.address()`", "name": "address", "type": "method", "meta": { "added": [ "v0.1.90" ], "changes": [ { "version": "v18.4.0", "pr-url": "https://github.com/nodejs/node/pull/43054", "description": "The `family` property now returns a string instead of a number." }, { "version": "v18.0.0", "pr-url": "https://github.com/nodejs/node/pull/41431", "description": "The `family` property now returns a number instead of a string." } ] }, "signatures": [ { "params": [], "return": { "textRaw": "Returns: {Object}", "name": "return", "type": "Object" } } ], "desc": "

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' }

" }, { "textRaw": "`socket.connect()`", "name": "connect", "type": "method", "signatures": [ { "params": [] } ], "desc": "

Initiate a connection on a given socket.

\n

Possible signatures:

\n\n

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.

\n

This function should only be used for reconnecting a socket after\n'close' has been emitted or otherwise it may lead to undefined\nbehavior.

", "methods": [ { "textRaw": "`socket.connect(options[, connectListener])`", "name": "connect", "type": "method", "meta": { "added": [ "v0.1.90" ], "changes": [ { "version": [ "v20.0.0", "v18.18.0" ], "pr-url": "https://github.com/nodejs/node/pull/46790", "description": "The default value for the autoSelectFamily option is now true. The `--enable-network-family-autoselection` CLI flag has been renamed to `--network-family-autoselection`. The old name is now an alias but it is discouraged." }, { "version": "v19.4.0", "pr-url": "https://github.com/nodejs/node/pull/45777", "description": "The default value for autoSelectFamily option can be changed at runtime using `setDefaultAutoSelectFamily` or via the command line option `--enable-network-family-autoselection`." }, { "version": [ "v19.3.0", "v18.13.0" ], "pr-url": "https://github.com/nodejs/node/pull/44731", "description": "Added the `autoSelectFamily` option." }, { "version": [ "v17.7.0", "v16.15.0" ], "pr-url": "https://github.com/nodejs/node/pull/41310", "description": "The `noDelay`, `keepAlive`, and `keepAliveInitialDelay` options are supported now." }, { "version": "v6.0.0", "pr-url": "https://github.com/nodejs/node/pull/6021", "description": "The `hints` option defaults to `0` in all cases now. Previously, in the absence of the `family` option it would default to `dns.ADDRCONFIG | dns.V4MAPPED`." }, { "version": "v5.11.0", "pr-url": "https://github.com/nodejs/node/pull/6000", "description": "The `hints` option is supported now." } ] }, "signatures": [ { "params": [ { "textRaw": "`options` {Object}", "name": "options", "type": "Object" }, { "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.", "optional": true } ], "return": { "textRaw": "Returns: {net.Socket} The socket itself.", "name": "return", "type": "net.Socket", "desc": "The socket itself." } } ], "desc": "

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.

\n

For TCP connections, available options are:

\n\n

For IPC connections, available options are:

\n" }, { "textRaw": "`socket.connect(path[, connectListener])`", "name": "connect", "type": "method", "signatures": [ { "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.", "optional": true } ], "return": { "textRaw": "Returns: {net.Socket} The socket itself.", "name": "return", "type": "net.Socket", "desc": "The socket itself." } } ], "desc": "

Initiate an IPC connection on the given socket.

\n

Alias to\nsocket.connect(options[, connectListener])\ncalled with { path: path } as options.

" }, { "textRaw": "`socket.connect(port[, host][, connectListener])`", "name": "connect", "type": "method", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`port` {number} Port the client should connect to.", "name": "port", "type": "number", "desc": "Port the client should connect to." }, { "textRaw": "`host` {string} Host the client should connect to.", "name": "host", "type": "string", "desc": "Host the client should connect to.", "optional": true }, { "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.", "optional": true } ], "return": { "textRaw": "Returns: {net.Socket} The socket itself.", "name": "return", "type": "net.Socket", "desc": "The socket itself." } } ], "desc": "

Initiate a TCP connection on the given socket.

\n

Alias to\nsocket.connect(options[, connectListener])\ncalled with {port: port, host: host} as options.

" } ] }, { "textRaw": "`socket.destroy([error])`", "name": "destroy", "type": "method", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`error` {Object}", "name": "error", "type": "Object", "optional": true } ], "return": { "textRaw": "Returns: {net.Socket}", "name": "return", "type": "net.Socket" } } ], "desc": "

Ensures that no more I/O activity happens on this socket.\nDestroys the stream and closes the connection.

\n

See writable.destroy() for further details.

" }, { "textRaw": "`socket.destroySoon()`", "name": "destroySoon", "type": "method", "meta": { "added": [ "v0.3.4" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

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().

" }, { "textRaw": "`socket.end([data[, encoding]][, callback])`", "name": "end", "type": "method", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`data` {string|Buffer|Uint8Array}", "name": "data", "type": "string|Buffer|Uint8Array", "optional": true }, { "textRaw": "`encoding` {string} Only used when data is `string`. **Default:** `'utf8'`.", "name": "encoding", "type": "string", "default": "`'utf8'`", "desc": "Only used when data is `string`.", "optional": true }, { "textRaw": "`callback` {Function} Optional callback for when the socket is finished.", "name": "callback", "type": "Function", "desc": "Optional callback for when the socket is finished.", "optional": true } ], "return": { "textRaw": "Returns: {net.Socket} The socket itself.", "name": "return", "type": "net.Socket", "desc": "The socket itself." } } ], "desc": "

Half-closes the socket. i.e., it sends a FIN packet. It is possible the\nserver will still send some data.

\n

See writable.end() for further details.

" }, { "textRaw": "`socket.pause()`", "name": "pause", "type": "method", "signatures": [ { "params": [], "return": { "textRaw": "Returns: {net.Socket} The socket itself.", "name": "return", "type": "net.Socket", "desc": "The socket itself." } } ], "desc": "

Pauses the reading of data. That is, 'data' events will not be emitted.\nUseful to throttle back an upload.

" }, { "textRaw": "`socket.ref()`", "name": "ref", "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": "

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.

" }, { "textRaw": "`socket.resetAndDestroy()`", "name": "resetAndDestroy", "type": "method", "meta": { "added": [ "v18.3.0", "v16.17.0" ], "changes": [] }, "signatures": [ { "params": [], "return": { "textRaw": "Returns: {net.Socket}", "name": "return", "type": "net.Socket" } } ], "desc": "

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.

" }, { "textRaw": "`socket.resume()`", "name": "resume", "type": "method", "signatures": [ { "params": [], "return": { "textRaw": "Returns: {net.Socket} The socket itself.", "name": "return", "type": "net.Socket", "desc": "The socket itself." } } ], "desc": "

Resumes reading after a call to socket.pause().

" }, { "textRaw": "`socket.setEncoding([encoding])`", "name": "setEncoding", "type": "method", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`encoding` {string}", "name": "encoding", "type": "string", "optional": true } ], "return": { "textRaw": "Returns: {net.Socket} The socket itself.", "name": "return", "type": "net.Socket", "desc": "The socket itself." } } ], "desc": "

Set the encoding for the socket as a Readable Stream. See\nreadable.setEncoding() for more information.

" }, { "textRaw": "`socket.setKeepAlive([enable][, initialDelay])`", "name": "setKeepAlive", "type": "method", "meta": { "added": [ "v0.1.92" ], "changes": [ { "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 } ], "return": { "textRaw": "Returns: {net.Socket} The socket itself.", "name": "return", "type": "net.Socket", "desc": "The socket itself." } } ], "desc": "

Enable/disable keep-alive functionality, and optionally set the initial\ndelay before the first keepalive probe is sent on an idle socket.

\n

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

\n

Enabling the keep-alive functionality will set the following socket options:

\n" }, { "textRaw": "`socket.setNoDelay([noDelay])`", "name": "setNoDelay", "type": "method", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`noDelay` {boolean} **Default:** `true`", "name": "noDelay", "type": "boolean", "default": "`true`", "optional": true } ], "return": { "textRaw": "Returns: {net.Socket} The socket itself.", "name": "return", "type": "net.Socket", "desc": "The socket itself." } } ], "desc": "

Enable/disable the use of Nagle's algorithm.

\n

When a TCP connection is created, it will have Nagle's algorithm enabled.

\n

Nagle's algorithm delays data before it is sent via the network. It attempts\nto optimize throughput at the expense of latency.

\n

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

" }, { "textRaw": "`socket.setTimeout(timeout[, callback])`", "name": "setTimeout", "type": "method", "meta": { "added": [ "v0.1.90" ], "changes": [ { "version": "v18.0.0", "pr-url": "https://github.com/nodejs/node/pull/41678", "description": "Passing an invalid callback to the `callback` argument now throws `ERR_INVALID_ARG_TYPE` instead of `ERR_INVALID_CALLBACK`." } ] }, "signatures": [ { "params": [ { "textRaw": "`timeout` {number}", "name": "timeout", "type": "number" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "optional": true } ], "return": { "textRaw": "Returns: {net.Socket} The socket itself.", "name": "return", "type": "net.Socket", "desc": "The socket itself." } } ], "desc": "

Sets the socket to timeout after timeout milliseconds of inactivity on\nthe socket. By default net.Socket do not have a timeout.

\n

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.

\n
socket.setTimeout(3000);\nsocket.on('timeout', () => {\n  console.log('socket timeout');\n  socket.end();\n});\n
\n

If timeout is 0, then the existing idle timeout is disabled.

\n

The optional callback parameter will be added as a one-time listener for the\n'timeout' event.

" }, { "textRaw": "`socket.getTypeOfService()`", "name": "getTypeOfService", "type": "method", "meta": { "added": [ "v25.6.0" ], "changes": [] }, "signatures": [ { "params": [], "return": { "textRaw": "Returns: {integer} The current TOS value.", "name": "return", "type": "integer", "desc": "The current TOS value." } } ], "desc": "

Returns the current Type of Service (TOS) field for IPv4 packets or Traffic\nClass for IPv6 packets for this socket.

\n

setTypeOfService() 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.

\n

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.

\n

setTypeOfService() 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.

\n

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.

" }, { "textRaw": "`socket.write(data[, encoding][, callback])`", "name": "write", "type": "method", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`data` {string|Buffer|Uint8Array}", "name": "data", "type": "string|Buffer|Uint8Array" }, { "textRaw": "`encoding` {string} Only used when data is `string`. **Default:** `utf8`.", "name": "encoding", "type": "string", "default": "`utf8`", "desc": "Only used when data is `string`.", "optional": true }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "optional": true } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "

Sends data on the socket. The second parameter specifies the encoding in the\ncase of a string. It defaults to UTF8 encoding.

\n

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

\n

The optional callback parameter will be executed when the data is finally\nwritten out, which may not be immediately.

\n

See Writable stream write() method for more\ninformation.

" } ], "properties": [ { "textRaw": "Type: {string[]}", "name": "autoSelectFamilyAttemptedAddresses", "type": "string[]", "meta": { "added": [ "v19.4.0", "v18.18.0" ], "changes": [] }, "desc": "

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.

\n

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.

" }, { "textRaw": "Type: {integer}", "name": "bufferSize", "type": "integer", "meta": { "added": [ "v0.3.8" ], "changes": [], "deprecated": [ "v14.6.0" ] }, "stability": 0, "stabilityText": "Deprecated: Use `writable.writableLength` instead.", "desc": "

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.

\n

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

\n

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().

" }, { "textRaw": "Type: {integer}", "name": "bytesRead", "type": "integer", "meta": { "added": [ "v0.5.3" ], "changes": [] }, "desc": "

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.

" }, { "textRaw": "Type: {boolean} Indicates if the connection is destroyed or not. Once a connection is destroyed no further data can be transferred using it.", "name": "destroyed", "type": "boolean", "desc": "

See writable.destroyed for further details.

", "shortDesc": "Indicates if the connection is destroyed or not. Once a connection is destroyed no further data can be transferred using it." }, { "textRaw": "Type: {string}", "name": "localAddress", "type": "string", "meta": { "added": [ "v0.9.6" ], "changes": [] }, "desc": "

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

" }, { "textRaw": "Type: {integer}", "name": "localPort", "type": "integer", "meta": { "added": [ "v0.9.6" ], "changes": [] }, "desc": "

The numeric representation of the local port. For example, 80 or 21.

" }, { "textRaw": "Type: {string}", "name": "localFamily", "type": "string", "meta": { "added": [ "v18.8.0", "v16.18.0" ], "changes": [] }, "desc": "

The string representation of the local IP family. 'IPv4' or 'IPv6'.

" }, { "textRaw": "Type: {boolean}", "name": "pending", "type": "boolean", "meta": { "added": [ "v11.2.0", "v10.16.0" ], "changes": [] }, "desc": "

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

" }, { "textRaw": "Type: {string}", "name": "remoteAddress", "type": "string", "meta": { "added": [ "v0.5.10" ], "changes": [] }, "desc": "

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

" }, { "textRaw": "Type: {string}", "name": "remoteFamily", "type": "string", "meta": { "added": [ "v0.11.14" ], "changes": [] }, "desc": "

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

" }, { "textRaw": "Type: {integer}", "name": "remotePort", "type": "integer", "meta": { "added": [ "v0.5.10" ], "changes": [] }, "desc": "

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

" }, { "textRaw": "Type: {number|undefined}", "name": "timeout", "type": "number|undefined", "meta": { "added": [ "v10.7.0" ], "changes": [] }, "desc": "

The socket timeout in milliseconds as set by socket.setTimeout().\nIt is undefined if a timeout has not been set.

" }, { "textRaw": "Type: {string}", "name": "readyState", "type": "string", "meta": { "added": [ "v0.5.0" ], "changes": [] }, "desc": "

This property represents the state of the connection as a string.

\n" } ] } ], "methods": [ { "textRaw": "`net.connect()`", "name": "connect", "type": "method", "signatures": [ { "params": [] } ], "desc": "

Aliases to\nnet.createConnection().

\n

Possible signatures:

\n", "methods": [ { "textRaw": "`net.connect(options[, connectListener])`", "name": "connect", "type": "method", "meta": { "added": [ "v0.7.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`options` {Object}", "name": "options", "type": "Object" }, { "textRaw": "`connectListener` {Function}", "name": "connectListener", "type": "Function", "optional": true } ], "return": { "textRaw": "Returns: {net.Socket}", "name": "return", "type": "net.Socket" } } ], "desc": "

Alias to\nnet.createConnection(options[, connectListener]).

" }, { "textRaw": "`net.connect(path[, connectListener])`", "name": "connect", "type": "method", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`path` {string}", "name": "path", "type": "string" }, { "textRaw": "`connectListener` {Function}", "name": "connectListener", "type": "Function", "optional": true } ], "return": { "textRaw": "Returns: {net.Socket}", "name": "return", "type": "net.Socket" } } ], "desc": "

Alias to\nnet.createConnection(path[, connectListener]).

" }, { "textRaw": "`net.connect(port[, host][, connectListener])`", "name": "connect", "type": "method", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`port` {number}", "name": "port", "type": "number" }, { "textRaw": "`host` {string}", "name": "host", "type": "string", "optional": true }, { "textRaw": "`connectListener` {Function}", "name": "connectListener", "type": "Function", "optional": true } ], "return": { "textRaw": "Returns: {net.Socket}", "name": "return", "type": "net.Socket" } } ], "desc": "

Alias to\nnet.createConnection(port[, host][, connectListener]).

" } ] }, { "textRaw": "`net.createConnection()`", "name": "createConnection", "type": "method", "signatures": [ { "params": [] } ], "desc": "

A factory function, which creates a new net.Socket,\nimmediately initiates connection with socket.connect(),\nthen returns the net.Socket that starts the connection.

\n

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.

\n

Possible signatures:

\n\n

The net.connect() function is an alias to this function.

", "methods": [ { "textRaw": "`net.createConnection(options[, connectListener])`", "name": "createConnection", "type": "method", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`options` {Object} Required. Will be passed to both the `new net.Socket([options])` call and the `socket.connect(options[, connectListener])` method.", "name": "options", "type": "Object", "desc": "Required. Will be passed to both the `new net.Socket([options])` call and the `socket.connect(options[, connectListener])` method." }, { "textRaw": "`connectListener` {Function} Common parameter of the `net.createConnection()` functions. If supplied, will be added as a listener for the `'connect'` event on the returned socket once.", "name": "connectListener", "type": "Function", "desc": "Common parameter of the `net.createConnection()` functions. If supplied, will be added as a listener for the `'connect'` event on the returned socket once.", "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": "

For available options, see\nnew net.Socket([options])\nand socket.connect(options[, connectListener]).

\n

Additional options:

\n\n

Following is an example of a client of the echo server described\nin the net.createServer() section:

\n
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
\n
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
\n

To connect on the socket /tmp/echo.sock:

\n
const client = net.createConnection({ path: '/tmp/echo.sock' });\n
\n

Following 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]).

\n
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
\n
const 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.

\n

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

" }, { "textRaw": "`net.createConnection(port[, host][, connectListener])`", "name": "createConnection", "type": "method", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`port` {number} Port the socket should connect to. Will be passed to `socket.connect(port[, host][, connectListener])`.", "name": "port", "type": "number", "desc": "Port the socket should connect to. Will be passed to `socket.connect(port[, host][, connectListener])`." }, { "textRaw": "`host` {string} Host the socket should connect to. Will be passed to `socket.connect(port[, host][, connectListener])`. **Default:** `'localhost'`.", "name": "host", "type": "string", "default": "`'localhost'`", "desc": "Host the socket should connect to. Will be passed to `socket.connect(port[, host][, connectListener])`.", "optional": true }, { "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(port[, host][, 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(port[, host][, 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 a TCP connection.

\n

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

" } ] }, { "textRaw": "`net.createServer([options][, connectionListener])`", "name": "createServer", "type": "method", "meta": { "added": [ "v0.5.0" ], "changes": [ { "version": [ "v20.1.0", "v18.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/47405", "description": "The `highWaterMark` option is supported now." }, { "version": [ "v17.7.0", "v16.15.0" ], "pr-url": "https://github.com/nodejs/node/pull/41310", "description": "The `noDelay`, `keepAlive`, and `keepAliveInitialDelay` options are supported now." } ] }, "signatures": [ { "params": [ { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`allowHalfOpen` {boolean} If set to `false`, then the socket will automatically end the writable side when the readable side ends. **Default:** `false`.", "name": "allowHalfOpen", "type": "boolean", "default": "`false`", "desc": "If set to `false`, then the socket will automatically end the writable side when the readable side ends." }, { "textRaw": "`highWaterMark` {number} Optionally overrides all `net.Socket`s' `readableHighWaterMark` and `writableHighWaterMark`. **Default:** See `stream.getDefaultHighWaterMark()`.", "name": "highWaterMark", "type": "number", "default": "See `stream.getDefaultHighWaterMark()`", "desc": "Optionally overrides all `net.Socket`s' `readableHighWaterMark` and `writableHighWaterMark`." }, { "textRaw": "`keepAlive` {boolean} If set to `true`, it enables keep-alive functionality on the socket immediately after a new incoming connection is received, similarly on what is done in `socket.setKeepAlive()`. **Default:** `false`.", "name": "keepAlive", "type": "boolean", "default": "`false`", "desc": "If set to `true`, it enables keep-alive functionality on the socket immediately after a new incoming connection is received, similarly on what is done in `socket.setKeepAlive()`." }, { "textRaw": "`keepAliveInitialDelay` {number} If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket. **Default:** `0`.", "name": "keepAliveInitialDelay", "type": "number", "default": "`0`", "desc": "If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket." }, { "textRaw": "`noDelay` {boolean} If set to `true`, it disables the use of Nagle's algorithm immediately after a new incoming connection is received. **Default:** `false`.", "name": "noDelay", "type": "boolean", "default": "`false`", "desc": "If set to `true`, it disables the use of Nagle's algorithm immediately after a new incoming connection is received." }, { "textRaw": "`pauseOnConnect` {boolean} Indicates whether the socket should be paused on incoming connections. **Default:** `false`.", "name": "pauseOnConnect", "type": "boolean", "default": "`false`", "desc": "Indicates whether the socket should be paused on incoming connections." }, { "textRaw": "`blockList` {net.BlockList} `blockList` can be used for disabling inbound access to specific IP addresses, IP ranges, or IP subnets. This does not work if the server is behind a reverse proxy, NAT, etc. because the address checked against the block list is the address of the proxy, or the one specified by the NAT.", "name": "blockList", "type": "net.BlockList", "desc": "`blockList` can be used for disabling inbound access to specific IP addresses, IP ranges, or IP subnets. This does not work if the server is behind a reverse proxy, NAT, etc. because the address checked against the block list is the address of the proxy, or the one specified by the NAT." } ], "optional": true }, { "textRaw": "`connectionListener` {Function} Automatically set as a listener for the `'connection'` event.", "name": "connectionListener", "type": "Function", "desc": "Automatically set as a listener for the `'connection'` event.", "optional": true } ], "return": { "textRaw": "Returns: {net.Server}", "name": "return", "type": "net.Server" } } ], "desc": "

Creates a new TCP or IPC server.

\n

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

\n

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().

\n

The server can be a TCP server or an IPC server, depending on what it\nlisten() to.

\n

Here is an example of a TCP echo server which listens for connections\non port 8124:

\n
import 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
\n
const 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
\n

Test this by using telnet:

\n
telnet localhost 8124\n
\n

To listen on the socket /tmp/echo.sock:

\n
server.listen('/tmp/echo.sock', () => {\n  console.log('server bound');\n});\n
\n

Use nc to connect to a Unix domain socket server:

\n
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.

" }, { "textRaw": "`net.setDefaultAutoSelectFamily(value)`", "name": "setDefaultAutoSelectFamily", "type": "method", "meta": { "added": [ "v19.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`value` {boolean} The new default value. The initial default value is `true`, unless the command line option `--no-network-family-autoselection` is provided.", "name": "value", "type": "boolean", "desc": "The new default value. The initial default value is `true`, unless the command line option `--no-network-family-autoselection` is provided." } ] } ], "desc": "

Sets the default value of the autoSelectFamily option of socket.connect(options).

" }, { "textRaw": "`net.getDefaultAutoSelectFamilyAttemptTimeout()`", "name": "getDefaultAutoSelectFamilyAttemptTimeout", "type": "method", "meta": { "added": [ "v19.8.0", "v18.18.0" ], "changes": [] }, "signatures": [ { "params": [], "return": { "textRaw": "Returns: {number} The current default value of the `autoSelectFamilyAttemptTimeout` option.", "name": "return", "type": "number", "desc": "The current default value of the `autoSelectFamilyAttemptTimeout` option." } } ], "desc": "

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.

" }, { "textRaw": "`net.setDefaultAutoSelectFamilyAttemptTimeout(value)`", "name": "setDefaultAutoSelectFamilyAttemptTimeout", "type": "method", "meta": { "added": [ "v19.8.0", "v18.18.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`value` {number} The new default value, which must be a positive number. If the number is less than `10`, the value `10` is used instead. The initial default value is `250` or the value specified via the command line option `--network-family-autoselection-attempt-timeout`.", "name": "value", "type": "number", "desc": "The new default value, which must be a positive number. If the number is less than `10`, the value `10` is used instead. The initial default value is `250` or the value specified via the command line option `--network-family-autoselection-attempt-timeout`." } ] } ], "desc": "

Sets the default value of the autoSelectFamilyAttemptTimeout option of socket.connect(options).

" }, { "textRaw": "`net.isIP(input)`", "name": "isIP", "type": "method", "meta": { "added": [ "v0.3.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`input` {string}", "name": "input", "type": "string" } ], "return": { "textRaw": "Returns: {integer}", "name": "return", "type": "integer" } } ], "desc": "

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.

\n
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)`", "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.

\n
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. Otherwise, returns false.

\n
net.isIPv6('::1'); // returns true\nnet.isIPv6('fhqwhgads'); // returns false\n
" } ], "displayName": "Net" } ] }
X Tutup