Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Pipe Response to a File in Co-Request module & NodeJs?

I am using Co-Request to read Zip file from http url, and i have below code to read from server..

The code works already. But I dont know how to write the response Zip to a file.

var co = require( "co" );
var request = require( "co-request" );
        var options = {
                        url: "http://www.example.com/sample.zip",
                        headers: {
                            'Token': Appconfig.Affiliate_Token,
                            'Affiliate-Id' : Appconfig.Affiliate_Id
                        }
                    }
                    console.log( "Downloading : zip file"  );
                    var j = yield request( options );

Co-Request is actually wrapper for Request and I have found below code to pipe file to stream. But not sure how to write the same using Co-Request with yield.

request.get('http://example.com/img.png').pipe(request.put('http://example.com/img.png'))

Please help how to write response zip to a file using yield and co-request

like image 701
amaz Avatar asked Apr 12 '15 04:04

amaz


People also ask

Which module is used for handling request and sending responses?

HTTP Module: The HTTP module is the built-in module that can be used without external installing command.

What is request and response in node?

Request and Response object both are the callback function parameters and are used for Express. js and Node. js. You can get the request query, params, body, headers, and cookies. It can overwrite any value or anything there.

What is a stream in node js?

A stream is an abstract interface for working with streaming data in Node.js. The node:stream module provides an API for implementing the stream interface. There are many stream objects provided by Node.js. For instance, a request to an HTTP server and process.stdout are both stream instances.


1 Answers

I think request cant pipe after data has been emitted from the response

use request instead of co-request, write a promise to achieve this

var co = require('co');
var request = require('request');
var fs = require('fs');

var url = 'http://google.com/doodle.png';

var requestPipToFile = function(url, filepath) {
    return new Promise(function(resolve, reject) {
        try {
            var stream = fs.createWriteStream(filepath);
            stream.on('finish', function() {
                console.log("pipe finish");
                return resolve(true);
            });
            return request(url).pipe(stream);
        } catch (e) {
            return reject(e);
        }
    });
};

co(function*() {
    var value = (yield requestPipToFile(url, './outfile'));
    return value;
}).then(function(value) {
    return console.log(value);
}).catch(function(err) {
    return console.error(err);
});
like image 150
Larvata Avatar answered Oct 18 '22 02:10

Larvata