0

How can I convert this curl operation using request Node.js library:

curl -L -X GET -H "Content-Type:application/json" -H "Authorization: authorization..." -H "Scope: 11111111" https://url/download >> file.gz

    /*the -L is curl option which means --location      Follow redirects (H)
         --location-trusted  Like '--location', and send auth to other hosts (H)*/

2 Answers 2

1

If you just want to download to a file, you can use a head request type.

The request will look like so:

request.head({
    url: "https://url/download",
    followAllRedirects: true,
    headers: {
    'Content-Type': 'application/json',
    'Authorization':'authorization...',
    'Scope': '11111111'
  }
}, (err, res, body) => {
  request('https://url/download')
    .pipe(fs.createWriteStream(`tmp/${res.path}`)).on('close', (data, err) => {
            if(err) console.log(`Unable to write to file ${err}`)
            console.log('Done')
    })
})

I have used a similar snippet which worked well

Use Postmans code generator

enter image description here

  1. Click code on the top left
  2. Paste your curl request
  3. Select Node.js Request from dropdown on top left of popup
  4. You should then get JS snippet converted from your working cURL request
Sign up to request clarification or add additional context in comments.

6 Comments

Thank you for your answer, but I get a file which contains 401 Unauthorized. I think I need the equivalent of -L of curl option because it works perfectly with the curl command but not with the request.
Have updated my answer and added option for followAllRedirects = true. Give that whirl
I still got the same error the res.path returns undefined and a file which contains <title>401 Unauthorized</title>... even if as I said it works perfectly with curl
Have you got postman? You can paste your curl request in the code snippet generator and then select Node.js Request from the drop down in the top left of the popup and it should create a javascript snippet for you.
Thank you, but even with postman's snippet it didn't work so strange but I found the solution which is request inside request.
|
0

Here is the solution we have to put request inside another because: so the first request returns the url and the second one will download the file

const options = {
  url: url,
  headers: {
    Authorization: `auth`,
    'scope': profileId,
    'content-type': 'application/json'
  },
};
const r = request.get(options, async (err, res, body) => {
    const fileStream = fs.createWriteStream(`${path}.gz`);
    request(res.request.uri.href).pipe(fileStream);
    // path exists unless there was an error
  });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.