Search code examples
node.jsexpressfilereadermulterpdf.js

fileReader.readAsArrayBuffer() equivalent method in Node.js?


I have a File object and I want to pass it to PDF.js's getDocument method. On the frontend I would use the getDocument method like so:

pdfjs.getDocument(fileReader.readAsArrayBuffer(myFileHere))

How can I implement the above with Node.js? I am also using Express.js and Multer.


Solution

  • I have no idea whether PDF.js is able to run on Node, but let's assume it is.

    At least with the readFile (or readFileSync if you prefer to be obtaining the contents "immediately") procedure available in Node, files may be read into Buffer objects, given the file's path.

    If you take a look at the documentation of Buffer linked above, you'll also find specified that these are instances of UInt8Array:

    The Buffer class is a subclass of JavaScript's Uint8Array class and extends it with methods that cover additional use cases.

    Going further, an object of the UInt8Array class, also being an object of the TypedArray class (by the same specification that specifies the former), has a property named buffer, which lets you access the, well, underlying buffer1 that is... an ArrayBuffer!

    So, you should be able to use a variation on the following, to pass an ArrayBuffer with some file's contents to PDF.js:

    pdfjs.getDocument(require("fs").readFileSync("/path/to/file").buffer);
    

    I have to assume you must read the file by path -- I assume your fileReader is a FileReader, which (contrary to its misleading name) reads Blob objects (and not files) -- and Node does not have any Blob class defined! So if you don't want to read the file by some path, then you'll have to tell us how you load file contents with Node at all.

    1 Don't blame me for the word "buffer" all over here, it's buffers all the way down, apparently -- I didn't design any of these classes ;)