Socket
Socket
Sign inDemoInstall

node-fetch

Package Overview
Dependencies
5
Maintainers
5
Versions
96
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 3.2.0 to 3.2.1

25

@types/index.d.ts
/// <reference types="node" />
/// <reference lib="dom" />
import {Agent} from 'http';
import {RequestOptions} from 'http';
import {
Blob,
blobFrom,
blobFromSync,
File,
fileFrom,
fileFromSync
} from 'fetch-blob/from.js';

@@ -15,2 +23,11 @@ type AbortSignal = {

export {
Blob,
blobFrom,
blobFromSync,
File,
fileFrom,
fileFromSync
};
/**

@@ -85,3 +102,3 @@ * This Fetch API interface allows you to perform various actions on HTTP request and response headers.

// Node-fetch extensions to the whatwg/fetch spec
agent?: Agent | ((parsedUrl: URL) => Agent);
agent?: RequestOptions['agent'] | ((parsedUrl: URL) => RequestOptions['agent']);
compress?: boolean;

@@ -118,5 +135,3 @@ counter?: number;

/**
* @deprecated Please use 'response.arrayBuffer()' instead of 'response.buffer()
*/
/** @deprecated Use `body.arrayBuffer()` instead. */
buffer(): Promise<Buffer>;

@@ -123,0 +138,0 @@ arrayBuffer(): Promise<ArrayBuffer>;

2

package.json
{
"name": "node-fetch",
"version": "3.2.0",
"version": "3.2.1",
"description": "A light-weight module that brings Fetch API to node.js",

@@ -5,0 +5,0 @@ "main": "./src/index.js",

@@ -67,2 +67,3 @@ <div align="center">

- [body.blob()](#bodyblob)
- [body.formData()](#formdata)
- [body.json()](#bodyjson)

@@ -142,9 +143,20 @@ - [body.text()](#bodytext)

// fetch-polyfill.js
import fetch from 'node-fetch';
import fetch, {
Blob,
blobFrom,
blobFromSync,
File,
fileFrom,
fileFromSync,
FormData,
Headers,
Request,
Response,
} from 'node-fetch'
if (!globalThis.fetch) {
globalThis.fetch = fetch;
globalThis.Headers = Headers;
globalThis.Request = Request;
globalThis.Response = Response;
globalThis.fetch = fetch
globalThis.Headers = Headers
globalThis.Request = Request
globalThis.Response = Response
}

@@ -164,3 +176,3 @@

- [1.x to 2.x upgrade guide](docs/v2-UPGRADE-GUIDE.md)
- [Changelog](docs/CHANGELOG.md)
- [Changelog](https://github.com/node-fetch/node-fetch/releases)

@@ -394,9 +406,17 @@ ## Common Usage

```js
import {fileFromSync} from 'fetch-blob/from.js';
import fetch from 'node-fetch';
import fetch {
Blob,
blobFrom,
blobFromSync,
File,
fileFrom,
fileFromSync,
} from 'node-fetch'
const blob = fileFromSync('./input.txt', 'text/plain');
const mimetype = 'text/plain'
const blob = fileFromSync('./input.txt', mimetype)
const url = 'https://httpbin.org/post'
const response = await fetch('https://httpbin.org/post', {method: 'POST', body: blob});
const data = await response.json();
const response = await fetch(url, { method: 'POST', body: blob })
const data = await response.json()

@@ -406,22 +426,46 @@ console.log(data)

node-fetch also supports any spec-compliant FormData implementations such as [formdata-polyfill](https://www.npmjs.com/package/formdata-polyfill). But any other spec-compliant such as [formdata-node](https://github.com/octet-stream/form-data) works too, but we recommend formdata-polyfill because we use this one internally for decoding entries back to FormData.
node-fetch comes with a spec-compliant [FormData] implementations for posting
multipart/form-data payloads
```js
import fetch from 'node-fetch';
import {FormData} from 'formdata-polyfill/esm.min.js';
import fetch, { FormData, File, fileFrom } from 'node-fetch'
// Alternative hack to get the same FormData instance as node-fetch
// const FormData = (await new Response(new URLSearchParams()).formData()).constructor
const httpbin = 'https://httpbin.org/post'
const formData = new FormData()
const binary = new Uint8Array([ 97, 98, 99 ])
const abc = new File([binary], 'abc.txt'), { type: 'text/plain' })
const form = new FormData();
form.set('greeting', 'Hello, world!');
formData.set('greeting', 'Hello, world!')
formData.set('file-upload', abc, 'new name.txt')
const response = await fetch('https://httpbin.org/post', {method: 'POST', body: form});
const data = await response.json();
const response = await fetch(httpbin, { method: 'POST', body: formData })
const data = await response.json()
console.log(data);
console.log(data)
```
node-fetch also support form-data but it's now discouraged due to not being spec-compliant and needs workarounds to function - which we hope to remove one day
If you for some reason need to post a stream coming from any arbitrary place,
then you can append a [Blob] or a [File] look-a-like item.
The minium requirement is that it has:
1. A `Symbol.toStringTag` getter or property that is either `Blob` or `File`
2. A known size.
3. And either a `stream()` method or a `arrayBuffer()` method that returns a ArrayBuffer.
The `stream()` must return any async iterable object as long as it yields Uint8Array (or Buffer)
so Node.Readable streams and whatwg streams works just fine.
```js
formData.append('upload', {
[Symbol.toStringTag]: 'Blob',
size: 3,
*stream() {
yield new Uint8Array([97, 98, 99])
},
arrayBuffer() {
return new Uint8Array([97, 98, 99]).buffer
}
}, 'abc.txt')
```
### Request cancellation with AbortSignal

@@ -434,3 +478,3 @@

```js
import fetch from 'node-fetch';
import fetch, { AbortError } from 'node-fetch';

@@ -449,3 +493,3 @@ // AbortController was added in node v14.17.0 globally

} catch (error) {
if (error instanceof fetch.AbortError) {
if (error instanceof AbortError) {
console.log('request was aborted');

@@ -699,4 +743,3 @@ }

const meta = {
'Content-Type': 'text/xml',
'Breaking-Bad': '<3'
'Content-Type': 'text/xml'
};

@@ -706,3 +749,3 @@ const headers = new Headers(meta);

// The above is equivalent to
const meta = [['Content-Type', 'text/xml'], ['Breaking-Bad', '<3']];
const meta = [['Content-Type', 'text/xml']];
const headers = new Headers(meta);

@@ -713,3 +756,2 @@

meta.set('Content-Type', 'text/xml');
meta.set('Breaking-Bad', '<3');
const headers = new Headers(meta);

@@ -751,8 +793,38 @@ const copyOfHeaders = new Headers(headers);

<small>_(spec-compliant)_</small>
`fetch` comes with methods to parse `multipart/form-data` payloads as well as
`x-www-form-urlencoded` bodies using `.formData()` this comes from the idea that
Service Worker can intercept such messages before it's sent to the server to
alter them. This is useful for anybody building a server so you can use it to
parse & consume payloads.
- Returns: `Promise`
<details>
<summary>Code example</summary>
Consume the body and return a promise that will resolve to one of these formats.
```js
import http from 'node:http'
import { Response } from 'node-fetch'
http.createServer(async function (req, res) {
const formData = await new Response(req, {
headers: req.headers // Pass along the boundary value
}).formData()
const allFields = [...formData]
const file = formData.get('uploaded-files')
const arrayBuffer = await file.arrayBuffer()
const text = await file.text()
const whatwgReadableStream = file.stream()
// other was to consume the request could be to do:
const json = await new Response(req).json()
const text = await new Response(req).text()
const arrayBuffer = await new Response(req).arrayBuffer()
const blob = await new Response(req, {
headers: req.headers // So that `type` inherits `Content-Type`
}.blob()
})
```
</details>
<a id="class-fetcherror"></a>

@@ -808,1 +880,4 @@

[error-handling.md]: https://github.com/node-fetch/node-fetch/blob/master/docs/ERROR-HANDLING.md
[FormData]: https://developer.mozilla.org/en-US/docs/Web/API/FormData
[Blob]: https://developer.mozilla.org/en-US/docs/Web/API/Blob
[File]: https://developer.mozilla.org/en-US/docs/Web/API/File

@@ -60,3 +60,3 @@ /**

if (parsedURL.username !== '' || parsedURL.password !== '') {
throw new TypeError(`${parsedURL} is an url with embedded credentails.`);
throw new TypeError(`${parsedURL} is an url with embedded credentials.`);
}

@@ -63,0 +63,0 @@

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc