Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send files with node.js

How do you send files on node.js/express.

I am using Rackspace Cloudfiles and wanna send images/videos to their remote storage but I am not sure that it's as simple as reading the file (fs.readFileSync()) and send the data in the request body, or is it?

What should the headers be.

What if it's a very large file on a couple of GBs?

Is it possible to use superagent (http://visionmedia.github.com/superagent) for this or is there a better library for sending files?

Please give me some information about this.

Thanks!

like image 501
ajsie Avatar asked Feb 17 '12 00:02

ajsie


3 Answers

app.get('/img/bg.png', function(req, res) {
  res.sendFile('public/img/background.png')
})

https://expressjs.com/en/api.html#res.sendFile

use "res.sendFile". "res.sendfile" is deprecated.

like image 78
denysonique Avatar answered Oct 11 '22 01:10

denysonique


For large files, you will want to use node.js's concept of piping IO streams together. You want to open the local file for reading, start the HTTP request to rackspace, and then pipe the data events from the file read process to the HTTP request process.

Here's an article on how to do this.

Superagent is fine for small files, but because the superagent API presumes your entire request body is loaded into memory before starting the request, it's not the best approach for large file transfers.

Normally you won't need to worry specifically about the request headers as node's HTTP request library will send the appropriate headers for you. Just make sure you use whatever HTTP method your API requires (probably POST), and it looks like for rackspace you will need to add the X-Auth-Token extra header with your API token as well.

like image 31
Peter Lyons Avatar answered Oct 11 '22 00:10

Peter Lyons


I am using Rackspace Cloudfiles and wanna send images/videos to their remote storage but I am not sure that it's as simple as reading the file (fs.readFileSync()) and send the data in the request body, or is it?

You should never use fs.readFileSync in general. When you use it, or any other method called somethingSync, you block the entire server for the duration of that call. The only acceptable time to make synchronous calls in a node.js program is during startup.

What should the headers be.

See RackSpace Cloud Files API.

Is it possible to use superagent (http://visionmedia.github.com/superagent) for this or is there a better library for sending files?

While I don't have any experience with superagent, I'm sure it will work fine. Just make sure you read the API documentation and make your requests according to their specification.

like image 5
Linus Thiel Avatar answered Oct 11 '22 01:10

Linus Thiel