Read remote file with node.js (http.get)

后端 未结 4 1506
野趣味
野趣味 2020-11-29 05:26

Whats the best way to read a remote file? I want to get the whole file (not chunks).

I started with the following example

var get = http.get(options)         


        
相关标签:
4条回答
  • 2020-11-29 06:12

    I'd use request for this:

    request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'))
    

    Or if you don't need to save to a file first, and you just need to read the CSV into memory, you can do the following:

    var request = require('request');
    request.get('http://www.whatever.com/my.csv', function (error, response, body) {
        if (!error && response.statusCode == 200) {
            var csv = body;
            // Continue with your processing here.
        }
    });
    

    etc.

    0 讨论(0)
  • 2020-11-29 06:22
    function(url,callback){
        request(url).on('data',(data) => {
            try{
                var json = JSON.parse(data);    
            }
            catch(error){
                callback("");
            }
            callback(json);
        })
    }
    

    You can also use this. This is to async flow. The error comes when the response is not a JSON. Also in 404 status code .

    0 讨论(0)
  • 2020-11-29 06:28

    You can do something like this, without using any external libraries.

    const fs = require("fs");
    const https = require("https");
    
    const file = fs.createWriteStream("data.txt");
    
    https.get("https://www.w3.org/TR/PNG/iso_8859-1.txt", response => {
      var stream = response.pipe(file);
    
      stream.on("finish", function() {
        console.log("done");
      });
    });
    
    0 讨论(0)
  • 2020-11-29 06:29
    http.get(options).on('response', function (response) {
        var body = '';
        var i = 0;
        response.on('data', function (chunk) {
            i++;
            body += chunk;
            console.log('BODY Part: ' + i);
        });
        response.on('end', function () {
    
            console.log(body);
            console.log('Finished');
        });
    });
    

    Changes to this, which works. Any comments?

    0 讨论(0)
提交回复
热议问题