Fetch only headers of a GET request in Node

∥☆過路亽.° 提交于 2019-12-01 13:19:35

问题


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

Unfortunately, the server I'm dealing with doesn't allow HEAD requests, and the files are too large to make an entire GET request.

I'm looking for something like this python code:

import requests

r = requests.get(url, stream=True)
content_length = r.headers['Content-Length']
content_type = r.headers['Content-Type']

The stream=True parameter means that the file won't be fully downloaded.


回答1:


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();
});



回答2:


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.



来源:https://stackoverflow.com/questions/44763985/fetch-only-headers-of-a-get-request-in-node

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!