How to Read a File on Backendless Server as ByteArray

Hello,

What would you recommend for opening a file that exists on the backendless server as a byte array, or readStream? My cloud service (JS) needs to open, then upload, the file to a third-part server (Quickbooks) by POSTing multipart/form-data, using Backendless.Request.

Is the node.js fs module allowed in cloud code? Or, is there a package you recommend that could simulate a Blob or the browser’s File object?

Any ideas or examples appreciated,

Kelly

Hello @Kelly_Oglesby,

here is an example of code that reads a file and returns it as ByteArray:

function encodePath(path) {
  if (path.startsWith('http://') || path.startsWith('https://')) {
    return path
  }

  let decodedPath

  try {
    decodedPath = decodeURI(path)
  } finally {
    return (decodedPath || path).split('/').map(encodeURIComponent).join('/')
  }
}

function readFileContent(result) {
  return result instanceof Buffer
    ? result.toJSON().data
    : Buffer.from(JSON.stringify(result)).toJSON().data
}

const pathToFile = encodePath('https://demo.com/path/to/file.txt')

const result = await Backendless.Request.get(pathToFile)
  .setEncoding(null)
  .then(result => readFileContent(null, result))

Regards,
Stanislaw