Skip to content
Advertisement

Read file on Discord from Dropbox location using JavaScript

I’m currently working on getting a Discord bot to connect to a directory inside of Dropbox, I’m using Discord.js and the Dropbox JavaScript SDK and I’ve done the following:

module.exports = {
  name: "dropbox",
  description: "Commands for interacting with a dropbox folder",
  execute(message, args) {
    var iso = require("isomorphic-fetch");
    var Dropbox = require("dropbox").Dropbox;
    var dbx = new Dropbox({ accessToken: "ACCESS_TOKEN", fetch: iso });
    dbx
      .filesListFolder({ path: "" })
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });
    dbx
      .filesDownload({ path: "/test.json" })
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });
  },
};

And I get the following response data:

{
  name: 'test.json',
  path_lower: '/test.json',
  path_display: '/test.json',
  id: 'id:rXD9HpHY8HAAAAAAAAAOEw',
  client_modified: '2020-08-24T20:29:51Z',
  server_modified: '2020-08-24T20:29:51Z',
  rev: '015ada572d4487c00000001e8da14d0',
  size: 45,
  is_downloadable: true,
  content_hash: '8864f0de005b2729263a68f88c1f2201049c0a37e5d4f033b3821d590d3a9f71',
  fileBinary: <Buffer 7b 0d 0a 20 20 22 76 61 6c 75 65 22 3a 20 22 54 68 69 73 20 69 73 20 61 20 74 65 73 74 20 4a 53 4f 4e 20 66 69 6c 65 22 0d 0a 7d 0d 0a>
}

But I’m unsure of how to proceed with this data, do I need to convert the content hash back to a json file? Or do I need to use the Node.js file streamer (fs) to access it? Which I feel would defeat the purpose of using the Dropbox SDK when I can use the API instead, or is there another way to read files that I need to download the package for?

I’m sorry if this is an obvious solution that I’m not getting, I can’t find any clear information on how to proceed and any information would be appreciated.

Advertisement

Answer

The Dropbox API JavaScript SDK does the work of communicating with the Dropbox API servers for you. In the case of downloading a file using filesDownload from the Dropbox SDK in Node, it makes the resulting file data available to you in the fileBinary field. You can read the data out from that Buffer, like in this example.

(The content_hash field is a “hash” of the file data, not the file data itself. You can find information on that here.)

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement