miniget - Small HTTP(S) GET Client
miniget is a lightweight HTTP(S) GET request library designed for both Node.js and browser environments, emphasizing minimal dependencies and a small footprint. It provides core functionalities like automatic redirects (up to 10 by default), request retries for 5xx or connection errors, and reconnects for interrupted downloads, allowing streams to resume. The current stable version is `4.2.3`, with releases typically addressing bug fixes and minor features rather than following a strict semantic versioning cadence between major versions. Key differentiators include its zero-dependency nature, support for streaming responses via a readable stream, and methods for concatenating responses into a single text body. It also exposes a configurable `defaultOptions` object for global settings and ships with TypeScript type definitions, making it well-suited for modern TypeScript projects.
Common errors
-
ReferenceError: require is not defined
cause Attempting to use `require()` in an ES module (ESM) context, typically indicated by `"type": "module"` in `package.json` or using `.mjs` file extensions.fixIf working in an ESM environment, use `import miniget from 'miniget';` instead of `const miniget = require('miniget');`. -
TypeError: miniget is not a function
cause Incorrect import statement. This usually happens when `miniget` is treated as a named export (`import { miniget } from 'miniget';`) when it is a default export, or when attempting an incorrect CommonJS import in an ESM file.fixFor ESM, use `import miniget from 'miniget';`. For CommonJS, use `const miniget = require('miniget');`. -
Stream error: Invalid URL
cause The URL string provided to `miniget` is malformed, not a valid `URL` object, or lacks a proper protocol (e.g., `http://` or `https://`).fixEnsure the URL parameter is a correctly formatted string (e.g., `https://example.com/resource`) or a valid `URL` object instance. -
Error: The 'close' event is no longer emitted from the miniget stream.
cause Your code is still attempting to listen for the `close` event on the `miniget` stream, which was removed as a breaking change in v4.0.0.fixRemove the `stream.on('close', ...)` listener from your code. If you need to detect stream completion, use `stream.on('end', ...)` or monitor the completion of downstream writable streams (e.g., `fileStream.on('finish', ...)`) if you are piping the data.
Warnings
- breaking The `close` event is no longer emitted from the miniget stream since v4.0.0. This change was implemented to prevent altering the stream's internal state and ensure proper finishing, aligning with Node.js stream best practices.
- breaking The `abort()` method was deprecated with a runtime warning in v3.0.0 and superseded by the `destroy()` method. The `destroy()` method was introduced to align more closely with Node.js's native HTTP request and stream destruction patterns.
- gotcha Prior to v4.2.1, `miniget` had a bug where it internally required the `url` module, which could cause issues when bundling with webpack for browser environments, leading to build failures or runtime errors.
- gotcha `miniget` is built for Node.js environments and declares `"node": ">=12"` in its `engines` field. Using it in older Node.js versions (e.g., Node.js 10 or 8) may result in unexpected behavior or runtime errors due to reliance on newer JavaScript features or Node.js APIs.
Install
-
npm install miniget -
yarn add miniget -
pnpm add miniget
Imports
- miniget
import { miniget } from 'miniget';import miniget from 'miniget';
- MinigetError
import MinigetError from 'miniget';
import { MinigetError } from 'miniget'; - Defaults
import { Defaults } from 'miniget';
Quickstart
import miniget from 'miniget';
import { createWriteStream } from 'node:fs';
async function fetchAndStreamData(url: string, filePath: string) {
try {
// Fetch and concatenate content as text
const textBody = await miniget(url).text();
console.log(`Fetched text from ${url.substring(0, 30)}... : ${textBody.substring(0, 50)}...`);
// Stream content to a file
const stream = miniget(url, { maxRedirects: 5, maxRetries: 1 });
stream.on('redirect', (newUrl) => console.log(`Redirected to: ${newUrl}`));
stream.on('error', (err) => console.error(`Stream error: ${err.message}`));
stream.on('response', (res) => console.log(`Received status: ${res.statusCode}`));
const fileStream = createWriteStream(filePath);
stream.pipe(fileStream);
await new Promise<void>((resolve, reject) => {
fileStream.on('finish', () => {
console.log(`Streamed content to ${filePath}`);
resolve();
});
fileStream.on('error', reject);
});
} catch (error: any) {
console.error(`Failed to fetch or stream: ${error.message}`);
}
}
// Example usage with a placeholder URL
// Replace with a valid URL for actual execution
const exampleUrl = 'https://jsonplaceholder.typicode.com/posts/1';
const outputFilePath = './output.json';
fetchAndStreamData(exampleUrl, outputFilePath);
// You can also modify global defaults
miniget.defaultOptions.headers = { 'User-Agent': 'miniget-example-app' };
console.log('Global User-Agent set.');