erikbrinkman / rmapi-js

JavaScript implementation of the reMarkable api
https://erikbrinkman.github.io/rmapi-js/modules.html
MIT License
9 stars 1 forks source link

Example on how to extract `ArrayBuffer` from files #9

Closed AlbertoHdezCerezo closed 8 months ago

AlbertoHdezCerezo commented 8 months ago

Hi! First of all thanks for maintaining this repo, I am looking forward to build some nice tools in reMarkable and this library looks promising.

I am trying to upload an epub via the uploadEpub method. When submitting a file, the request is successful, but when trying to open the submitted file on my reMarkable device, I get an error message (it complains of being unable to open the file).

My gut feeling is that I am not passing the right ArrayBuffer to the request. I am trying to find examples in the docs of how to get a buffer from a file via Node.js, but I have not found anything. This is how I am currently trying to read the file in my project:

async function readFileAsArrayBuffer (filePath: string): Promise<ArrayBuffer> {
  const data = await fs.readFile(filePath)
  return data.buffer
}

The returning values are what I am passing to await api.uploadEpub("name", buffer);.

Is there something I am doing wrong when extracting the body?

erikbrinkman commented 8 months ago

Looking at the problem, and the documentation of node's buffers, it seems that you need to apply the offset to get it to work, e.g.

const buff = await readFile("...");
const upload = new Uint8Array(buff.buffer, buff.byteOffset, buff.length);

However, when I was playing around, it seems that the node buffer also works. typescript might complain, which likely means I need to update my interfaces, but if this is for your own work, I would just return the node buffer and stop worrying!

AlbertoHdezCerezo commented 8 months ago

Thank you for the clarification! You were absolutely right, the Node.js readFile method returns a compatible buffer that can upload the file:

/**
 * @jest-environment node
 */
import { promises as fs } from 'fs'
import { register, remarkable } from 'rmapi-js'

async function readFileAsArrayBuffer (filePath: string): Promise<ArrayBuffer> {
  return await fs.readFile(filePath)
}

describe('FileManager', () => {
  describe('.uploadEpub', () => {
    it('if valid epub file is provided, uploads file', async () => {
      const buffer = await readFileAsArrayBuffer('./test/fixtures/documents/sample.epub')
      const token = await register(...)
      const api = await remarkable(token)
      await api.uploadEpub('cacahue', buffer)
    }, 1000000)
  })
})

The problem was due to my jest configuration and test environment when running the tests.