How to download a binary file using Axios

Sep 20, 2017 using tags axios, nodejs

If you’re not already familiar, the axios library is a really well done abstraction on top of raw XHR requests.

In a way the simplicity of its API reminds me of the Python Requests library, which was why we chose to use axios in both the frontend & backend code at Switchboard.

I could not originally figure out how to download a binary file using axios in a Node.js environment so hopefully this little snippet is useful to the next person who looks this up.

import axios from 'axios';
import fs from 'fs';

// ...

return axios.request({
  responseType: 'arraybuffer',
  url: 'http://www.example.com/file.mp3',
  method: 'get',
  headers: {
    'Content-Type': 'audio/mpeg',
  },
}).then((result) => {
  const outputFilename = '/tmp/file.mp3';
  fs.writeFileSync(outputFilename, result.data);
  return outputFilename;
});

The trick is here is to set the responseType to arraybuffer and then write the chained promise output data to a file on disk.