Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js send file to client

Hello there I have been trying to send a file from node.js to the client.

My code works however when the client goes to the specified url (/helloworld/hello.js/test) it streams the file.

Accessing it from Google Chrome makes the file (.mp3) play in a player.

My goal is to have the client's browser download the file and ask the client where he wants to store it, not stream it on the website.

http.createServer(function(req, res) {
    switch (req.url) {
        case '/helloworld/hello.js/test':

            var filePath = path.join(__dirname, '/files/output.mp3');
            var stat = fileSystem.statSync(filePath);

            res.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.on('open', function() {
                // This just pipes the read stream to the response object (which goes to the client)
                readStream.pipe(res);
            });

            readStream.on('error', function(err) {
                res.end(err);
            });
    }
});
like image 811
Marat Arguinbaev Avatar asked Feb 05 '14 13:02

Marat Arguinbaev


People also ask

How do I send data from server to client in node JS?

Methods to send response from server to client are:Using send() function. Using json() function.

How do I download a file from a node js server?

Method 1: Using 'https' and 'fs' module We can use the http GET method to fetch the files that are to be downloaded. The createWriteStream() method from fs module creates a writable stream and receives the argument with the location of the file where it needs to be saved.

What is __ Dirname in node?

It gives the current working directory of the Node. js process. __dirname: It is a local variable that returns the directory name of the current module. It returns the folder path of the current JavaScript file.


1 Answers

You need to set some header flags;

res.writeHead(200, {
    'Content-Type': 'audio/mpeg',
    'Content-Length': stat.size,
    'Content-Disposition': 'attachment; filename=your_file_name'
});

For replacing streaming with download;

var file = fs.readFile(filePath, 'binary');

res.setHeader('Content-Length', stat.size);
res.setHeader('Content-Type', 'audio/mpeg');
res.setHeader('Content-Disposition', 'attachment; filename=your_file_name');
res.write(file, 'binary');
res.end();
like image 81
Hüseyin BABAL Avatar answered Oct 12 '22 23:10

Hüseyin BABAL