diff --git a/doc/api/net.md b/doc/api/net.md index b5310b10665302..6d4b864b30f249 100644 --- a/doc/api/net.md +++ b/doc/api/net.md @@ -825,6 +825,16 @@ added: v0.5.3 The amount of bytes sent. +### `socket.writeQueueSize` + + + +* {integer} + +The amount of bytes in libuv write queue. + ### `socket.connect()` Initiate a connection on a given socket. diff --git a/lib/net.js b/lib/net.js index 548e5e7878a56b..4ac8578f300d51 100644 --- a/lib/net.js +++ b/lib/net.js @@ -967,6 +967,9 @@ protoGetter('bytesWritten', function bytesWritten() { return bytes; }); +protoGetter('writeQueueSize', function writeQueueSize() { + return this._handle ? this._handle.writeQueueSize : -1; +}); function checkBindError(err, port, handle) { // EADDRINUSE may not be reported until we call listen() or connect(). diff --git a/test/parallel/test-net-connect-write-queue-size.js b/test/parallel/test-net-connect-write-queue-size.js new file mode 100644 index 00000000000000..e912d5bdb8ed4a --- /dev/null +++ b/test/parallel/test-net-connect-write-queue-size.js @@ -0,0 +1,31 @@ +'use strict'; +const common = require('../common'); +const assert = require('assert'); +const net = require('net'); +const tmpdir = require('../common/tmpdir'); + +tmpdir.refresh(); + +const socket = new net.Socket(); +assert.strictEqual(socket.writeQueueSize, -1); + +const server = net.createServer() + .listen(common.PIPE, common.mustCall(() => { + // The pipe connection is a synchronous operation + // `net.connect` will set `socket.connecting` to true + const socket = net.connect(common.PIPE, common.mustCall(() => { + socket.destroy(); + server.close(); + })); + // Set connecting to false here to make `socket.write` can call into + // libuv directly (see `_writeGeneric` in `net.js`). + // because the socket is connecting currently in libuv, so libuv will + // insert the write request into write queue, then we can get the + // size of write queue by `socket.writeQueueSize`. + socket.connecting = false; + const data = 'hello'; + socket.write(data, 'utf-8', common.mustCall()); + assert.strictEqual(socket.writeQueueSize, common.isWindows ? 0 : data.length); + // Restore it + socket.connecting = true; + }));