{"_id":"@achingbrain/electron-fetch","_rev":"4576661","name":"@achingbrain/electron-fetch","description":"A light-weight module that brings window.fetch to electron's background process","dist-tags":{"latest":"1.7.2"},"maintainers":[{"name":"achingbrain","email":"alex@achingbrain.net"}],"time":{"modified":"2026-04-10T15:44:55.000Z","created":"2020-10-09T13:48:47.760Z","1.7.2":"2020-10-09T13:48:47.760Z"},"users":{},"author":{"name":"Mehdi Kouhen"},"repository":{"type":"git","url":"git+https://github.com/arantes555/electron-fetch.git"},"versions":{"1.7.2":{"name":"@achingbrain/electron-fetch","version":"1.7.2","description":"A light-weight module that brings window.fetch to electron's background process","main":"lib/index.js","module":"lib/index.es.js","types":"index.d.ts","engines":{"node":">=6"},"scripts":{"build":"cross-env BABEL_ENV=rollup rollup -c","prepublishOnly":"npm run build","lint":"standard","test":"npm run test:electron && npm run test:node && npm run test:typings && standard","pretest:typings":"npm run build","test:typings":"ts-node test/test-typescript.ts","test:electron":"xvfb-maybe cross-env BABEL_ENV=test electron-mocha --require @babel/register test/test.js","test:node":"cross-env BABEL_ENV=test mocha --require @babel/register test/test.js","coverage":"xvfb-maybe cross-env BABEL_ENV=coverage electron-mocha --require @babel/register test/test.js --reporter test/coverage-reporter.js","report":"npm run lint && npm run test:typings && npm run coverage && codecov -f coverage/coverage-final.json"},"repository":{"type":"git","url":"git+https://github.com/arantes555/electron-fetch.git"},"keywords":["fetch","http","promise","electron"],"author":{"name":"Mehdi Kouhen"},"license":"MIT","bugs":{"url":"https://github.com/arantes555/electron-fetch/issues"},"homepage":"https://github.com/arantes555/electron-fetch","devDependencies":{"@babel/core":"^7.11.5","@babel/preset-env":"^7.11.5","@babel/register":"^7.11.5","abortcontroller-polyfill":"^1.5.0","babel-eslint":"^10.1.0","babel-plugin-istanbul":"^6.0.0","basic-auth-parser":"0.0.2","chai":"^4.2.0","chai-as-promised":"^7.1.1","codecov":"^3.7.2","cross-env":"^7.0.2","electron":"^10.1.1","electron-mocha":"^9.1.0","form-data":"^3.0.0","is-builtin-module":"^3.0.0","istanbul-api":"^3.0.0","istanbul-lib-coverage":"^3.0.0","mocha":"^8.1.3","nyc":"^15.1.0","parted":"^0.1.1","promise":"^8.1.0","proxy":"^1.0.2","resumer":"0.0.0","rollup":"^2.26.9","rollup-plugin-babel":"^4.4.0","standard":"^14.3.4","ts-node":"^9.0.0","typescript":"^4.0.2","whatwg-url":"^8.2.1","xvfb-maybe":"^0.2.1"},"dependencies":{"encoding":"^0.1.13"},"gitHead":"5814a006665cc093f9c817300044ba107a2f2095","_id":"@achingbrain/electron-fetch@1.7.2","_nodeVersion":"12.16.1","_npmVersion":"6.14.1","dist":{"shasum":"df48e7e33b217520be1abb5bef151828fef7cf73","size":31245,"noattachment":false,"key":"/@achingbrain/electron-fetch/-/@achingbrain/electron-fetch-1.7.2.tgz","tarball":"http://registry.cnpm.dingdandao.com/@achingbrain/electron-fetch/download/@achingbrain/electron-fetch-1.7.2.tgz"},"maintainers":[{"name":"achingbrain","email":"alex@achingbrain.net"}],"_npmUser":{"name":"achingbrain","email":"alex@achingbrain.net"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/electron-fetch_1.7.2_1602251327592_0.041239946197130894"},"_hasShrinkwrap":false,"publish_time":1602251327760,"_cnpm_publish_time":1602251327760,"_cnpmcore_publish_time":"2021-12-16T13:35:38.733Z"}},"readme":"\nelectron-fetch\n==========\n\n[![npm version][npm-image]][npm-url]\n[![build status][travis-image]][travis-url]\n[![coverage status][codecov-image]][codecov-url]\n\nA light-weight module that brings `window.fetch` to Electron's background process.\nForked from [`node-fetch`](https://github.com/bitinn/node-fetch).\n\n## Motivation\n\nInstead of implementing `XMLHttpRequest` over Electron's `net` module to run browser-specific [Fetch polyfill](https://github.com/github/fetch), why not go from native `net.request` to `fetch` API directly? Hence `electron-fetch`, minimal code for a `window.fetch` compatible API on Electron's background runtime.\n\nWhy not simply use node-fetch? Well, Electron's `net` module does a better job than Node.js' `http` module at handling web proxies.\n\n\n## Features\n\n- Stay consistent with `window.fetch` API.\n- Runs on both Electron and Node.js, using either Electron's `net` module, or Node.js `http` module as backend.\n- Make conscious trade-off when following [whatwg fetch spec][whatwg-fetch] and [stream spec](https://streams.spec.whatwg.org/) implementation details, document known difference.\n- Use native promise.\n- Use native stream for body, on both request and response.\n- Decode content encoding (gzip/deflate) properly, and convert string output (such as `res.text()` and `res.json()`) to UTF-8 automatically.\n- Useful extensions such as timeout, redirect limit (when running on Node.js), response size limit, [explicit errors][] for troubleshooting.\n\n\n## Difference from client-side fetch\n\n- See [Known Differences](https://github.com/arantes555/electron-fetch/blob/master/LIMITS.md) for details.\n- If you happen to use a missing feature that `window.fetch` offers, feel free to open an issue.\n- Pull requests are welcomed too!\n\n\n## Difference from node-fetch\n\n- Removed node-fetch specific options, such as `compression`.\n- Added electron-specific options to specify the `Session` & to enable using cookies from it.\n- Added electron-specific option `useElectronNet`, which can be set to false when running on Electron in order to behave as Node.js.\n- Removed possibility to use custom Promise implementation (it's 2018, `Promise` is available everywhere!).\n- Removed the possibility to forbid content compression (incompatible with Electron's `net` module, and of limited interest)\n- [`standard`-ized](http://standardjs.com) the code.\n\n## Install\n\n```sh\n$ npm install electron-fetch --save\n```\n\n\n## Usage\n\n```javascript\nimport fetch from 'electron-fetch'\n// or\n// const fetch = require('electron-fetch').default\n\n// plain text or html\n\nfetch('https://github.com/')\n\t.then(res => res.text())\n\t.then(body => console.log(body))\n\n// json\n\nfetch('https://api.github.com/users/github')\n\t.then(res => res.json())\n\t.then(json => console.log(json))\n\n// catching network error\n// 3xx-5xx responses are NOT network errors, and should be handled in then()\n// you only need one catch() at the end of your promise chain\n\nfetch('http://domain.invalid/')\n\t.catch(err => console.error(err))\n\n// stream\n// the node.js way is to use stream when possible\n\nfetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png')\n\t.then(res => {\n\t\tconst dest = fs.createWriteStream('./octocat.png')\n\t\tres.body.pipe(dest)\n\t})\n\n// buffer\n// if you prefer to cache binary data in full, use buffer()\n// note that buffer() is a electron-fetch only API\n\nimport fileType from 'file-type'\n\nfetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png')\n\t.then(res => res.buffer())\n\t.then(buffer => fileType(buffer))\n\t.then(type => { /* ... */ })\n\n// meta\n\nfetch('https://github.com/')\n\t.then(res => {\n\t\tconsole.log(res.ok)\n\t\tconsole.log(res.status)\n\t\tconsole.log(res.statusText)\n\t\tconsole.log(res.headers.raw())\n\t\tconsole.log(res.headers.get('content-type'))\n\t})\n\n// post\n\nfetch('http://httpbin.org/post', { method: 'POST', body: 'a=1' })\n\t.then(res => res.json())\n\t.then(json => console.log(json))\n\n// post with stream from file\n\nimport { createReadStream } from 'fs'\n\nconst stream = createReadStream('input.txt')\nfetch('http://httpbin.org/post', { method: 'POST', body: stream })\n\t.then(res => res.json())\n\t.then(json => console.log(json))\n\n// post with JSON\n\nconst body = { a: 1 }\nfetch('http://httpbin.org/post', { \n\tmethod: 'POST',\n\tbody:    JSON.stringify(body),\n\theaders: { 'Content-Type': 'application/json' },\n})\n\t.then(res => res.json())\n\t.then(json => console.log(json))\n\n// post with form-data (detect multipart)\n\nimport FormData from 'form-data'\n\nconst form = new FormData()\nform.append('a', 1)\nfetch('http://httpbin.org/post', { method: 'POST', body: form })\n\t.then(res => res.json())\n\t.then(json => console.log(json))\n\n// post with form-data (custom headers)\n// note that getHeaders() is non-standard API\n\nimport FormData from 'form-data'\n\nconst form = new FormData()\nform.append('a', 1)\nfetch('http://httpbin.org/post', { method: 'POST', body: form, headers: form.getHeaders() })\n\t.then(res => res.json())\n\t.then(json => console.log(json))\n\n// node 7+ with async function\n\n(async function () {\n\tconst res = await fetch('https://api.github.com/users/github')\n\tconst json = await res.json()\n\tconsole.log(json)\n})()\n```\n\nSee [test cases](https://github.com/arantes555/electron-fetch/blob/master/test/test.js) for more examples.\n\n\n## API\n\n### fetch(url[, options])\n\n- `url` A string representing the URL for fetching\n- `options` [Options](#fetch-options) for the HTTP(S) request\n- Returns: <code>Promise&lt;[Response](#class-response)&gt;</code>\n\nPerform an HTTP(S) fetch.\n\n`url` should be an absolute url, such as `http://example.com/`. A path-relative URL (`/file/under/root`) or protocol-relative URL (`//can-be-http-or-https.com/`) will result in a rejected promise.\n\n<a id=\"fetch-options\"></a>\n#### Options\n\nThe default values are shown after each option key.\n\n```js\nconst defaultOptions = {\n\t// These properties are part of the Fetch Standard\n\tmethod: 'GET',\n\theaders: {},        // request headers. format is the identical to that accepted by the Headers constructor (see below)\n\tbody: null,         // request body. can be null, a string, a Buffer, a Blob, or a Node.js Readable stream\n\tredirect: 'follow', // (/!\\ only works when running on Node.js) set to `manual` to extract redirect headers, `error` to reject redirect\n    signal: null,       // the AbortSignal from an AbortController instance.\n\n\t// The following properties are electron-fetch extensions\n\tfollow: 20,         // (/!\\ only works when running on Node.js) maximum redirect count. 0 to not follow redirect\n\ttimeout: 0,         // req/res timeout in ms, it resets on redirect. 0 to disable (OS limit applies)\n\tsize: 0,            // maximum response body size in bytes. 0 to disable\n\tsession: session.defaultSession, // (/!\\ only works when running on Electron) Electron Session object.,\n\tagent: null,        // (/!\\ only works when useElectronNet is false) Node HTTP Agent.,\n\tuseElectronNet: true, // When running on Electron, defaults to true. On Node.js, defaults to false and cannot be set to true.\n\tuseSessionCookies: true, // (/!\\ only works when running on Electron >= 7) Whether or not to automatically send cookies from session.,\n\tuser: undefined,    // When running on Electron behind an authenticated HTTP proxy, username to use to authenticate\n\tpassword: undefined // When running on Electron behind an authenticated HTTP proxy, password to use to authenticate\n}\n```\n\n##### Default Headers\n\nIf no values are set, the following request headers will be sent automatically:\n\nHeader            | Value\n----------------- | --------------------------------------------------------\n`Accept-Encoding` | `gzip,deflate`\n`Accept`          | `*/*`\n`Connection`      | `close`\n`Content-Length`  | _(automatically calculated, if possible)_\n`User-Agent`      | `electron-fetch/1.0 (+https://github.com/arantes555/electron-fetch)`\n\n<a id=\"class-request\"></a>\n### Class: Request\n\nAn HTTP(S) request containing information about URL, method, headers, and the body. This class implements the [Body](#iface-body) interface.\n\nDue to the nature of Node.js, the following properties are not implemented at this moment:\n\n- `type`\n- `destination`\n- `referrer`\n- `referrerPolicy`\n- `mode`\n- `credentials`\n- `cache`\n- `integrity`\n- `keepalive`\n\nThe following electron-fetch extension properties are provided:\n\n- `follow` (/!\\ only works when running on Node.js)\n- `counter` (/!\\ only works when running on Node.js)\n- `session` (/!\\ only works when running on Electron)\n- `agent` (/!\\ only works when running on Node.js)\n- `useElectronNet` (/!\\ only works when running on Electron, throws when set to true on Node.js)\n- `useSessionCookies` (/!\\ only works when running on Electron >= 7)\n\nSee [options](#fetch-options) for exact meaning of these extensions.\n\n#### new Request(input[, options])\n\n<small>*(spec-compliant)*</small>\n\n- `input` A string representing a URL, or another `Request` (which will be cloned)\n- `options` [Options][#fetch-options] for the HTTP(S) request\n\nConstructs a new `Request` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request).\n\nIn most cases, directly `fetch(url, options)` is simpler than creating a `Request` object.\n\n<a id=\"class-response\"></a>\n### Class: Response\n\nAn HTTP(S) response. This class implements the [Body](#iface-body) interface.\n\nThe following properties are not implemented in electron-fetch at this moment:\n\n- `Response.error()`\n- `Response.redirect()`\n- `type`\n- `redirected`\n- `trailer`\n\n#### new Response([body[, options]])\n\n<small>*(spec-compliant)*</small>\n\n- `body` A string or [Readable stream][node-readable]\n- `options` A [`ResponseInit`][response-init] options dictionary\n\nConstructs a new `Response` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response).\n\nBecause Node.js & Electron's background do not implement service workers (for which this class was designed), one rarely has to construct a `Response` directly.\n\n<a id=\"class-headers\"></a>\n### Class: Headers\n\nThis class allows manipulating and iterating over a set of HTTP headers. All methods specified in the [Fetch Standard][whatwg-fetch] are implemented.\n\n#### new Headers([init])\n\n<small>*(spec-compliant)*</small>\n\n- `init` Optional argument to pre-fill the `Headers` object\n\nConstruct a new `Headers` object. `init` can be either `null`, a `Headers` object, an key-value map object, or any iterable object.\n\n```js\n// Example adapted from https://fetch.spec.whatwg.org/#example-headers-class\n\nconst meta = {\n  'Content-Type': 'text/xml',\n  'Breaking-Bad': '<3'\n}\nconst headers = new Headers(meta)\n\n// The above is equivalent to\nconst meta = [\n  [ 'Content-Type', 'text/xml' ],\n  [ 'Breaking-Bad', '<3' ]\n]\nconst headers = new Headers(meta)\n\n// You can in fact use any iterable objects, like a Map or even another Headers\nconst meta = new Map()\nmeta.set('Content-Type', 'text/xml')\nmeta.set('Breaking-Bad', '<3')\nconst headers = new Headers(meta)\nconst copyOfHeaders = new Headers(headers)\n```\n\n<a id=\"iface-body\"></a>\n### Interface: Body\n\n`Body` is an abstract interface with methods that are applicable to both `Request` and `Response` classes.\n\nThe following methods are not yet implemented in electron-fetch at this moment:\n\n- `formData()`\n\n#### body.body\n\n<small>*(deviation from spec)*</small>\n\n* Node.js [`Readable` stream][node-readable]\n\nThe data encapsulated in the `Body` object. Note that while the [Fetch Standard][whatwg-fetch] requires the property to always be a WHATWG `ReadableStream`, in electron-fetch it is a Node.js [`Readable` stream][node-readable].\n\n#### body.bodyUsed\n\n<small>*(spec-compliant)*</small>\n\n* `Boolean`\n\nA boolean property for if this body has been consumed. Per spec, a consumed body cannot be used again.\n\n#### body.arrayBuffer()\n#### body.blob()\n#### body.json()\n#### body.text()\n\n<small>*(spec-compliant)*</small>\n\n* Returns: <code>Promise</code>\n\nConsume the body and return a promise that will resolve to one of these formats.\n\n#### body.buffer()\n\n<small>*(electron-fetch extension)*</small>\n\n* Returns: <code>Promise&lt;Buffer&gt;</code>\n\nConsume the body and return a promise that will resolve to a Buffer.\n\n#### body.textConverted()\n\n<small>*(electron-fetch extension)*</small>\n\n* Returns: <code>Promise&lt;String&gt;</code>\n\nIdentical to `body.text()`, except instead of always converting to UTF-8, encoding sniffing will be performed and text converted to UTF-8, if possible.\n\n<a id=\"class-fetcherror\"></a>\n### Class: FetchError\n\n<small>*(electron-fetch extension)*</small>\n\nAn operational error in the fetching process. See [ERROR-HANDLING.md][] for more info.\n\n## License\n\nMIT\n\n\n## Acknowledgement\n\nThanks to [github/fetch](https://github.com/github/fetch) for providing a solid implementation reference.\nThanks to [node-fetch](https://github.com/bitinn/node-fetch) for providing a solid base to fork.\n\n\n[npm-image]: https://img.shields.io/npm/v/electron-fetch.svg?style=flat-square\n[npm-url]: https://www.npmjs.com/package/electron-fetch\n[travis-image]: https://img.shields.io/travis/arantes555/electron-fetch.svg?style=flat-square\n[travis-url]: https://travis-ci.org/arantes555/electron-fetch\n[codecov-image]: https://img.shields.io/codecov/c/github/arantes555/electron-fetch.svg?style=flat-square\n[codecov-url]: https://codecov.io/gh/arantes555/electron-fetch\n[ERROR-HANDLING.md]: https://github.com/arantes555/electron-fetch/blob/master/ERROR-HANDLING.md\n[whatwg-fetch]: https://fetch.spec.whatwg.org/\n[response-init]: https://fetch.spec.whatwg.org/#responseinit\n[node-readable]: https://nodejs.org/api/stream.html#stream_readable_streams\n[mdn-headers]: https://developer.mozilla.org/en-US/docs/Web/API/Headers\n","_attachments":{},"homepage":"https://github.com/arantes555/electron-fetch","bugs":{"url":"https://github.com/arantes555/electron-fetch/issues"},"license":"MIT"}