How to save octet stream received as REST response to the file system?

8.3k Views Asked by At

While trying to save octet stream JSON format response (containing data of file in a properietary format) received using Unirest client the format gets corrupted and the (properietary) software used to open that format is unable to open this saved file. Data encoding mismatch error is received.

The same works perfectly fine when the REST call is driven via nodejs based POSTMAN chrome app.

Any clues or leads to this.

Following is the code used to receive octet stream in nodejs:

urClient.get(url)
    .header('Authorization', '<token>')
    .header('Content-Type', 'application/json')
    .end(
        function(response) {
            log.info('+++++++++++++++'+response.code);
            //log.info('+++++++++++++++'+response);
            //log.info('+++++++++++++++'+response.body);
            //log.info('+++++++++++++++'+response.keys);
            fs.writeFile(`${destination}\\${fileName}.${fileExtension}`, response.data, function (error) {
                if (error) {
                    response = {
                        "error": error
                    };
                    res.statusCode = 400;
                    res.json(response); }
            });
        });
1

There are 1 best solutions below

0
On BEST ANSWER

Instead of data, the stream needs to be used to be written into a file.

The following works:

fs.writeFile(`response.txt`, response.stream, function (error) {
  if (error) { console.error(error); }
});