What is undici?
The undici npm package is a HTTP/1.1 client, written from scratch for Node.js, that is designed to be faster and more efficient than the built-in 'http' and 'https' modules. It provides a low-level API for making HTTP requests and can be used to build higher-level abstractions.
What are undici's main functionalities?
HTTP Request
Make an HTTP request and process the response. This is the basic functionality of undici, allowing you to send HTTP requests and receive responses.
const { request } = require('undici');
(async () => {
const { statusCode, headers, body } = await request('https://example.com')
console.log('response received', statusCode);
for await (const data of body) {
console.log('data', data);
}
})();
HTTP Pool
Use a pool of connections to make HTTP requests. This is useful for making a large number of requests to the same server, as it reuses connections between requests.
const { Pool } = require('undici');
const pool = new Pool('https://example.com')
async function query() {
const { body } = await pool.request({
path: '/path',
method: 'GET'
})
for await (const data of body) {
console.log('data', data);
}
}
query();
HTTP Stream
Stream an HTTP response to a file or another stream. This is useful for handling large responses that you don't want to hold in memory.
const { pipeline } = require('undici');
const fs = require('fs');
pipeline(
'https://example.com',
fs.createWriteStream('output.txt'),
(err) => {
if (err) {
console.error('Pipeline failed', err);
} else {
console.log('Pipeline succeeded');
}
}
);
HTTP Upgrade
Upgrade an HTTP connection to another protocol, such as WebSockets. This is useful for protocols that start with an HTTP handshake and then upgrade to a different protocol.
const { connect } = require('undici');
(async () => {
const { socket, statusCode, headers } = await connect({
path: '/path',
method: 'GET'
});
console.log('upgrade response', statusCode, headers);
socket.on('data', (chunk) => {
console.log('data', chunk.toString());
});
})();
Other packages similar to undici
axios
Axios is a promise-based HTTP client for the browser and Node.js. It provides a simple API for making HTTP requests and is often used for its ease of use and wide adoption. Compared to undici, axios is higher-level and more feature-rich, but may not be as performant for certain use cases.
got
Got is a human-friendly and powerful HTTP request library for Node.js. It supports streams, promises, and provides a rich set of features for making HTTP requests. Got is similar to undici in terms of performance but offers a more comprehensive API surface.
node-fetch
node-fetch is a light-weight module that brings the Fetch API to Node.js. It is designed to mimic the browser fetch API as closely as possible. While undici focuses on HTTP/1.1, node-fetch provides a familiar interface for those used to working with fetch in the browser.
undici
An HTTP/1.1 client, written from scratch for Node.js.
Undici means eleven in Italian. 1.1 -> 11 -> Eleven -> Undici.
It is also a Stranger Things reference.
Install
npm i undici
API
new undici.Client(url, opts)
A basic HTTP/1.1 client, mapped on top a single TCP/TLS connection.
Keepalive is enabled by default, and it cannot be turned off.
The url
will be used to extract the protocol and the domain/IP
address. The path is discarded.
Options:
-
timeout
, the timeout after which a request will time out, in
milliseconds. Default:
30000
milliseconds.
-
pipelining
, the amount of concurrent requests to be sent over the
single TCP/TLS connection according to
RFC7230. Default: 1
.
client.request(opts, cb(err, data))
Performs an HTTP request.
Options:
path
method
body
, it can be a String
, a Buffer
or a stream.Readable
.headers
, an object with header-value pairs.
The data
parameter in the callback is defined as follow:
statusCode
headers
body
, a stream.Readable
with the body to read. A user must
call data.body.resume()
Example:
const { Client } = require('undici')
const client = new Client(`http://localhost:3000`)
client.request({
path: '/',
method: 'GET'
}, function (err, data) {
if (err) {
return
}
const {
statusCode,
headers,
body
} = data
console.log('response received', statusCode)
console.log('headers', headers)
body.setEncoding('utf8')
body.on('data', console.log)
client.close()
})
Promises and async await are supported as well!
const { statusCode, headers, body } = await client.request({
path: '/',
method: 'GET'
})
client.pipelining
Property to set the pipelining factor.
client.full
True if the number of requests waiting to be sent is greater
than the pipelining factor. Keeping a client full ensures that once the
inflight set of requests finishes there is a full batch ready to go.
client.close()
Close the client as soon as all the enqueued requests are completed
client.destroy(err)
Destroy the client abruptly with the given err
. All the current and
enqueued requests will error.
Events
'drain'
, emitted when the queue is empty.
undici.Pool
A pool of Client
connected to the same upstream target.
A pool creates a fixed number of Client
Options:
connections
, the number of clients to create. Default 100
.pipelining
, the pipelining factor. Default 1
.timeout
, the timeout for each request. Default 30000
milliseconds.
pool.request(req, cb)
Calls client.request(req, cb)
on one of the clients.
pool.close()
Calls client.close()
on all the clients.
pool.destroy()
Calls client.destroy()
on all the clients.
License
MIT