bams
bams

Reputation: 612

how to do this curl operation in Node.js using request library

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)*/

Upvotes: 0

Views: 883

Answers (2)

bams
bams

Reputation: 612

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

Upvotes: 0

Stretch0
Stretch0

Reputation: 9253

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

Upvotes: 1

Related Questions