Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Nodejs send file in response

Nodejs send file in response

Problem

Expressjs framework has a sendfile() method. How can I do that without using a whole framework. I am using node-native-zip to create an archive and I want to Send that to the user.

Problem courtesy of: andrei

Solution

Here's an example program that will send myfile.mp3 by streaming it from disk (that is, it doesn't read the whole file into memory before sending the file). The server listens on port 2000.

[Update] As mentioned by @Aftershock in the comments, util.pump is gone and was replaced with a method on the Stream prototype called pipe; the code below reflects this.

var http = require('http'),
    fileSystem = require('fs'),
    path = require('path');

http.createServer(function(request, response) {
    var filePath = path.join(__dirname, 'myfile.mp3');
    var stat = fileSystem.statSync(filePath);

    response.writeHead(200, {
        'Content-Type': 'audio/mpeg',
        'Content-Length': stat.size
    });

    var readStream = fileSystem.createReadStream(filePath);
    // We replaced all the event handlers with a simple call to readStream.pipe()
    readStream.pipe(response);
})
.listen(2000);

Taken from http://elegantcode.com/2011/04/06/taking-baby-steps-with-node-js-pumping-data-between-streams/

Solution courtesy of: Michelle Tilley

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Nodejs send file in response

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×