Ensure that getDocument handles Node.js Buffers more gracefully (issue 13075)

While the JSDocs have never advertised `getDocument` as supporting Node.js `Buffer`s, that apparently doesn't stop users from passing such data structures to `getDocument`.
In theory the existing `instanceof Uint8Array` check ought to have caught Node.js `Buffer`s, however for reasons that I don't even pretend to understand that check actually passes. Hence this patch which, *only* in Node.js environments, will special-case `Buffer`s to hopefully provide a slightly better out-of-the-box behaviour in Node.js environments[1].

---
[1] Although I'm not sure that we necessarily want to advertise this in the JSDocs, given the specialized use-case.
This commit is contained in:
Jonas Jenwald 2021-03-10 23:13:55 +01:00
parent 61318c42aa
commit 50681d71c8

View File

@ -243,10 +243,21 @@ function getDocument(src) {
} else if (key === "worker") {
worker = source[key];
continue;
} else if (key === "data" && !(source[key] instanceof Uint8Array)) {
} else if (key === "data") {
// Converting string or array-like data to Uint8Array.
const pdfBytes = source[key];
if (typeof pdfBytes === "string") {
if (
typeof PDFJSDev !== "undefined" &&
PDFJSDev.test("GENERIC") &&
isNodeJS &&
typeof Buffer !== "undefined" && // eslint-disable-line no-undef
pdfBytes instanceof Buffer // eslint-disable-line no-undef
) {
params[key] = new Uint8Array(pdfBytes);
} else if (pdfBytes instanceof Uint8Array) {
// Use the data as-is when it's already a Uint8Array.
params[key] = pdfBytes;
} else if (typeof pdfBytes === "string") {
params[key] = stringToBytes(pdfBytes);
} else if (
typeof pdfBytes === "object" &&
@ -259,8 +270,7 @@ function getDocument(src) {
} else {
throw new Error(
"Invalid PDF binary data: either typed array, " +
"string or array-like object is expected in the " +
"data property."
"string, or array-like object is expected in the data property."
);
}
continue;