Bogdan Lungu
Bogdan Lungu

Reputation: 786

Firebase cloud functions: how to retrieve a file from an FTP account and download it in the browser

I have an app which has Firebase as a back-end. From within this app I connect to a FTP server. The connection to the FTP server is done using Firebase Cloud functions and the jsftp module (https://github.com/sergi/jsftp). I have done tests and it works well to browse the files, create files or folder and upload new files. I got stuck with how to retrieve files from the server. In the jsftp module there is the get() method that is doing this and it is working like that:

var str = ""; // Will store the contents of the file
ftp.get("remote/path/file.txt", (err, socket) => {
  if (err) {
    return;
  }

  socket.on("data", d => {
    str += d.toString();
  });

  socket.on("close", err => {
    if (hadErr) console.error("There was an error retrieving the file.");
  });

  socket.resume();
});

The documentation says like this: Gives back a paused socket with the file contents ready to be streamed, or calls the callback with an error if not successful.

As I have limited experience with Nodejs and socket my question is: How can I retrieve the file using this "socket" and make it available for download in the browser. So when I call the Firebase Cloud function it should return the file. Is that possible? 

Thanks in advance!

Upvotes: 2

Views: 2343

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317758

Here's a complete index.js with a function that downloads a readme from an Apache mirror using jsftp and sends it back to the client. Note that it's making an outgoing socket connection, which means you need to run it in a project on the paid Blaze plan.

const functions = require('firebase-functions')
const JSFtp = require('jsftp')

exports.getFtp = functions.https.onRequest((req, res) => {
    const ftp = new JSFtp({
        host: 'mirrors.ocf.berkeley.edu'
    });

    ftp.get('/apache/commons/beanutils/RELEASE-NOTES.txt', (err, socket) => {
        if (err) {
            res.send(500).send(err)
        }

        socket.on('data', data => {
            res.write(data.toString())
        })

        socket.on('close', err => {
            if (err) {
                console.error("There was an error retrieving the file", err)
            }
            else {
                res.end()
            }
        })

        socket.resume()
    })
})

Upvotes: 2

Related Questions