Or Smith
Or Smith

Reputation: 3616

node.js & Express / Read stream and write to client

I have the next code in the server side:

client.getFile(url.substring(1, url.length), function (err, res) {
 var outputStream1 = fs.createWriteStream("./tmp/" + url);
 res.on('data', function (chunk) {
                    outputStream1.write(chunk);
                });
  res.on('end', function () {
                    outputStream1.end();
                    // I got the response in the parameters function. It refer to the res express param
                    response.setHeader("content-type", 'application/octet-stream;charset=utf-8');
                    response.setHeader("content-type", 'application/octet-stream;charset=utf-8');
                    response.setHeader("Content-Disposition", 'attachment; filename="' + fileName + '"' + "; filename*=UTF-8''" + fileName + "");
                    var readStream = fs.createReadStream("./tmp/" + url);
                    fs.stat("./tmp/" + url, function(error, stat) {
                        console.log("The size of the file is: " + stat.size);
                    })
                    readStream.on('open', function () {
                        readStream.pipe(response);
                    });
                    readStream.on('end', function () {
                        response.end();
                    });

and the output is: The size of the file is: 5992213

Now I sent the request from the server to the client, and want to save it into file, so I do the next in the CLIENT side:

  var post_req = http.request(post_options, function(res) {
        res.setEncoding('utf8');
        var writeStream = fs.createWriteStream("C://Client//create.pdf");
        fs.stat("C://ClientFile//something5.pdf", function(error, stat) {
        res.pipe(writeStream);
    });

But I see that the file which save is 10.4 MB, and when I open it, the next error is shown:"File is out of memory"

What I do wrong?

Upvotes: 2

Views: 5683

Answers (1)

cieszynka
cieszynka

Reputation: 91

In your router, set url to download the file

app.get('/url-to-file.pdf', callback);

and then, in callback function use res.download, like this:

callback = function(req, res){
            res.download('server/path/to/file');
        }

You can write this as

app.get('/url-to-file.pdf', function(req, res){
            res.download('server/path/to/file');
        });

on client site just run the url : domain/url-to-file.pdf

most problems, in this solution, can be dynamic generation of the url

Upvotes: 1

Related Questions