Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to get headers only? #771

Closed
gajus opened this issue Apr 10, 2019 · 6 comments
Closed

How to get headers only? #771

gajus opened this issue Apr 10, 2019 · 6 comments
Labels
question The issue is a question about Got

Comments

@gajus
Copy link
Contributor

gajus commented Apr 10, 2019

I want to make a request, read headers, follow redirects if such occur, but do not download the body.

The use case is to expand shortened URLs.

Sometimes shortened URLs can link to large files.

I guess this requires a resolveHeadersOnly option.

@sindresorhus
Copy link
Owner

Can you do a HEAD request? That would not fetch the body.

@gajus
Copy link
Contributor Author

gajus commented Apr 10, 2019

That was the first thing I tried.

Unfortunately, some URLs return "Method Not Allowed" when you do HEAD request, e.g. any http://gcr.io/ URLs.

@gajus
Copy link
Contributor Author

gajus commented Apr 10, 2019

It is fine if whatever the approach would download some of the body. I just want to make sure that I don't end up downloading some random 1GB zip files.

@szmarczak
Copy link
Collaborator

got.stream('http://gcr.io/').on('response', response => {
    console.log(response.headers);
}).resume();

It will download the file, but will not save it. It's gonna be removed immediately.

@gajus
Copy link
Contributor Author

gajus commented Apr 10, 2019

Good suggestion, but unfortunately this would be a huge waste of bandwidth, esp. at a scale that I am doing this.

@szmarczak
Copy link
Collaborator

szmarczak commented Apr 10, 2019

unfortunately this would be a huge waste of bandwidth

So you do not want do download data. In other words you don't want to keep the connection, that means you want to cancel the request:

const getHeaders = () => new Promise((resolve, reject) => {
    const promise = got('http://gcr.io/').on('response', response => {
        resolve(response.headers);
        promise.cancel();
    });
    
    promise.then(response => resolve(response.headers)).catch(reject);
});

(async () => {
    console.log(await getHeaders());
})();

Note that you need to cancel ONLY when you're not being redirected, because you will break the chain otherwise.

I hope this solves your problem :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question The issue is a question about Got
Projects
None yet
Development

No branches or pull requests

3 participants