-1

I am completely lost here regarding this.

I have a custom API where the endpoint is /api and my client NodeJS script calls towards this endpoint with some form data.

Let's say my client sends a POST with the parameters download_file and file_id, how would the web server respond with the file data?

I'm sure someone has solved this before but I can't find any information about this.

vaid
  • 1,390
  • 12
  • 33
  • There's a method on Express called [`res.sendFile`](https://expressjs.com/en/api.html#res.sendFile). Does that not work for you? – d4nyll Apr 28 '20 at 23:08
  • @e4nyll I don't know. I have a full duplex issue here. SendFile works fine for normal web stuff but would it also work when POSTing from a NodeJS client too? If yes, which I assume, what would the NodeJS client code look like? I'm looking at `request` but I just can't figure out how to make the server and client interact. – vaid Apr 28 '20 at 23:21
  • Well, `POST` is just a HTTP verb like `GET` but with different semantics. It is just another parameter, like path, for your server to know which handler to use. The `res.X` methods specifies what data you send back. How you receive a request and how you send back a response are two totally separate things. As from the client's side, you can use the [fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API), a library like [axios](https://github.com/axios/axios) or [superagent](https://visionmedia.github.io/superagent/). For saving the file - https://stackoverflow.com/a/51302466 – d4nyll Apr 28 '20 at 23:40

1 Answers1

0

In the client script where you're going to download the file there are multiple steps you need to do:

  1. create a writestream to a file
  2. make a request to the server
  3. pipe the response stream to the file write stream

The code would look something like the following:

const request = require('request');
const fs = require('fs');

request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'))

  • This makes sense, and I think I read this somewhere earlier. This makes me wonder: How would the filename be passed on with the actual data of the file? Pipe only passes the file content, but what about the filename? – vaid Apr 28 '20 at 23:55
  • The file name could be passed in the `Content-Disposition` header. Check express `res.attachment` and `res.type` methods. You can manipulate the code to get the file name and type from the headers and use them to create your downloaded file. – GreatPyrenees Apr 29 '20 at 00:29