urllib for Node.js
urllib is a comprehensive HTTP client library for Node.js, designed to simplify URL interactions in complex scenarios. It provides features like basic and digest authentication, automatic redirection handling, configurable timeouts, and support for various request and response data types. The current stable version is 4.9.0, with a parallel maintenance branch for version 3 (latest 3.27.3). The library is built on top of Node.js's `undici` API, offering modern performance and adherence to web standards. It has a regular release cadence, with frequent bug fixes and minor feature additions across both major versions. Key differentiators include its robust handling of HTTP complexities often found in enterprise environments and its strong TypeScript support.
Common errors
-
SyntaxError: Named export 'request' not found. The requested module 'urllib' does not provide an export named 'request'
cause Attempting to use ES module `import` syntax in a Node.js CommonJS module, or running in an older Node.js version not configured for ESM.fixFor Node.js CommonJS files, change `import { request } from 'urllib';` to `const { request } = require('urllib');`. If you intend to use ESM, ensure your `package.json` has `"type": "module"` or files end with `.mjs`. -
TypeError: Cannot destructure property 'data' of 'undefined' or 'null' as it is null.
cause Missing `await` keyword when calling `urllib.request`, causing the result to be a Promise instead of the resolved value.fixEnsure you `await` the `request` call: `const { data, res } = await request(...);`. Remember that `await` can only be used inside `async` functions. -
Error: connect ETIMEDOUT <IP>:<PORT>
cause The network connection timed out before a response could be established or fully received.fixIncrease the `timeout` option in `request` (e.g., `timeout: 10000` milliseconds). Verify network connectivity and firewall rules. The target server might be down or heavily loaded. -
SyntaxError: Unexpected token '"', "{ "error": "In"..." is not valid JSONcause The `dataType: 'json'` option was used, but the server responded with non-JSON content or malformed JSON. The error message indicates an attempt to parse a string that starts like JSON but is invalid or unexpected.fixInspect the raw response content (e.g., by logging `data.toString()`) to understand why it's not valid JSON. You might need to remove `dataType: 'json'` and manually parse the `data` buffer/string after checking `res.headers['content-type']` or handle non-JSON responses gracefully.
Warnings
- breaking urllib v4 introduces significant internal changes by basing its API on `undici`, which may lead to subtle behavioral differences or require Node.js 18.19.0+. While the `request` API remains largely consistent, deep integrations or reliance on internal `urllib` behaviors might require adjustments.
- breaking The `compressed` option, which controls automatic decompression of response bodies, changed its default value to `false`. Previously, it might have defaulted to `true` or been implicitly handled, leading to uncompressed responses if not explicitly set.
- gotcha The `timeout` option in `urllib` historically had variations in how it accepted string formats (e.g., '2s'). While v4.7.1 added compatibility for `urllib@2` string formats, relying on number-based timeouts (milliseconds) is the most robust and consistent approach across versions.
- deprecated The direct `urllib` class constructor or `new urllib()` pattern is generally deprecated in favor of named exports like `request` for simple calls or `create` for custom instances. Relying on default exports or class instantiation can lead to unexpected behavior or future breakage.
- gotcha Security vulnerabilities in `urllib` or its dependencies are tracked by Snyk. While the library actively addresses them, it's crucial to regularly update to the latest patch versions to mitigate known risks.
Install
-
npm install urllib -
yarn add urllib -
pnpm add urllib
Imports
- request
const { request } = require('urllib'); // Incorrect in a pure ESM module contextimport { request } from 'urllib'; - request (CommonJS)
import { request } from 'urllib'; // Incorrect in a CommonJS module contextconst { request } = require('urllib'); - create (for custom instance)
import urllib from 'urllib'; // Default import is not the primary API const client = new urllib(); // Class instantiation is not the recommended pattern
import { create } from 'urllib'; const client = create({ /* options */ });
Quickstart
import { request } from 'urllib';
async function fetchData() {
try {
const { data, res } = await request('https://cnodejs.org/api/v1/topics?limit=5', {
dataType: 'json', // Automatically parse response as JSON
method: 'GET',
timeout: 5000, // 5 seconds timeout
headers: {
'User-Agent': 'urllib-checklist-example/1.0'
}
});
console.log('Status: %s', res.status);
console.log('Headers: %j', res.headers);
console.log('First topic title: %s', data.data[0].title);
} catch (error) {
console.error('Request failed:', error.message);
}
}
fetchData();