Fetch only headers of a GET request in Node

后端 未结 3 1736
感情败类
感情败类 2021-01-15 18:40

I need to get the Content-Length and Content-Type headers of large files with Node.

Unfortunately, the server I\'m dealing with do

相关标签:
3条回答
  • 2021-01-15 19:05

    Use method: 'HEAD':

    http.request('http://example.com', {
        method: 'HEAD',
    }, res => {
        console.log(res.statusCode, res.statusMessage)
        console.log(res.headers)
    
        res.on('data', _ => {
            console.log(`IT SHOULDN'T REACH HERE!`)
        })
    }).on('error', console.error)
      .end()
    
    0 讨论(0)
  • 2021-01-15 19:08

    If you're using the request package, you could do something like this:

    const request = require('request');
    const r = request(url);
    r.on('response', response => {
        const contentLength = response.headers['content-length'];
        const contentType = response.headers['content-type'];
        // ...
        r.abort();
    });
    
    0 讨论(0)
  • 2021-01-15 19:25

    The http library of nodejs by default it will not fetch everything but give the callback will contain the IncomingMessage object, to construct the full response you would have to listen to .on('data').

    Take a look at:

    https://nodejs.org/api/http.html#http_http_get_options_callback

    If you then want to "ignore" the incoming data, you can just call res.abort(). Calling this will cause remaining data in the response to be dropped and the socket to be destroyed.

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