[api-minor] Use the Fetch API, when supported, to load PDF documents in Node.js environments

Given that modern Node.js versions now implement support for a fair number of "browser" APIs, we can utilize the standard Fetch API to load PDF documents that are specified via http/https URLs.

Please find compatibility information at:
 - https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API#browser_compatibility
 - https://nodejs.org/dist/latest-v18.x/docs/api/globals.html#fetch
 - https://developer.mozilla.org/en-US/docs/Web/API/Response#browser_compatibility
 - https://nodejs.org/dist/latest-v18.x/docs/api/globals.html#response
This commit is contained in:
Jonas Jenwald 2024-02-21 16:04:13 +01:00
parent 72b8b29147
commit eded037d06
6 changed files with 123 additions and 54 deletions

View file

@ -13,16 +13,40 @@
* limitations under the License.
*/
import { AbortException } from "../../src/shared/util.js";
import { AbortException, isNodeJS } from "../../src/shared/util.js";
import { createTemporaryNodeServer } from "./test_utils.js";
import { PDFFetchStream } from "../../src/display/fetch_stream.js";
describe("fetch_stream", function () {
const pdfUrl = new URL("../pdfs/tracemonkey.pdf", window.location).href;
let tempServer = null;
function getPdfUrl() {
return isNodeJS
? `http://127.0.0.1:${tempServer.port}/tracemonkey.pdf`
: new URL("../pdfs/tracemonkey.pdf", window.location).href;
}
const pdfLength = 1016315;
beforeAll(function () {
if (isNodeJS) {
tempServer = createTemporaryNodeServer();
}
});
afterAll(function () {
if (isNodeJS) {
// Close the server from accepting new connections after all test
// finishes.
const { server } = tempServer;
server.close();
tempServer = null;
}
});
it("read with streaming", async function () {
const stream = new PDFFetchStream({
url: pdfUrl,
url: getPdfUrl(),
disableStream: false,
disableRange: true,
});
@ -57,7 +81,7 @@ describe("fetch_stream", function () {
it("read ranges with streaming", async function () {
const rangeSize = 32768;
const stream = new PDFFetchStream({
url: pdfUrl,
url: getPdfUrl(),
rangeChunkSize: rangeSize,
disableStream: false,
disableRange: false,