I am trying to download a file from Google Drive using the Google SDK API using node.js.
But I can not write / save the file on the server side - node.js
The code: -
var GoogleTokenProvider = require("refresh-token").GoogleTokenProvider, async = require('async'), fs = require("fs"), request = require('request'), _accessToken; var _XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest; var https = require('https'); const CLIENT_ID = ""; const CLIENT_SECRET = ""; const REFRESH_TOKEN = ''; const ENDPOINT_OF_GDRIVE = 'https://www.googleapis.com/drive/v2'; async.waterfall([ //----------------------------- // Obtain a new access token //----------------------------- function(callback) { var tokenProvider = new GoogleTokenProvider({ 'refresh_token': REFRESH_TOKEN, 'client_id': CLIENT_ID, 'client_secret': CLIENT_SECRET }); tokenProvider.getToken(callback); }, //-------------------------------------------- // Retrieve the children in a specified folder // // ref: https://developers.google.com/drive/v2/reference/files/children/list //------------------------------------------- function(accessToken, callback) { _accessToken = accessToken; request.get({ 'url': ENDPOINT_OF_GDRIVE + '/files?' + "q='root' in parents and (mimeType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document')", 'qs': { 'access_token': accessToken } }, callback); }, //---------------------------- // Parse the response //---------------------------- function(response, body, callback) { var list = JSON.parse(body); if (list.error) { return callback(list.error); } callback(null, list.items[0]); }, //------------------------------------------- // Get the file information of the children. // // ref: https://developers.google.com/drive/v2/reference/files/get //------------------------------------------- function(children, callback) { var xhr = new _XMLHttpRequest(); xhr.open('GET', children.downloadUrl); xhr.setRequestHeader('Authorization', 'Bearer ' + _accessToken); xhr.onload = function() { console.log("xhr.responseText", xhr.responseText) fs.writeFile("download.docx", xhr.responseText) callback(xhr.responseText); }; xhr.onerror = function() { callback(null); }; xhr.send(); } ], function(err, results) { if (!err) { console.log(results); } });
I get this in the console : - The content of xhr.responseText is something like this
▬h ↕E6M ~ 3 3∟ 9 ► /2 : ♂ 4 ] ♀I R ► $SB6Q c↔ H =;+ ►q 3Tdכ @!T hEl_ | I ↨ h( ^:▬ [h̓D♠ f ♠* ݾ M→ 1⌂♦"N ↑ o ] 7U$ A6 ♠ W k` f▬♫ K Z ^‼ 0{<Z ▼ ]F J♥A♀ ♣ a }7 " H w" ♥ ☺w♫̤ھ P ^ O֛ ; <♠ aYՠ؛`G kxm PY [ g Gΰino /< < 1 ⳆA$>"f3 \ ȾT ∟IS W♥ Y
Please help me find out what format of data I get from Api Disk and write it in which format to get the full .docx file
Edit
I am open to using any method other than xmlRequest if it helps me upload a file (.docx).
source share