Node.js Google Drive: Download a File (Stream to the Filesystem)

Back to Index

Downloads the content of a file by ID. (In this example the file id = 1R_70heIyzIAu1_u0prXbYcaIiJRVkgBl) The file is streamed directly to the filesystem. Note: The alt=media query param must be used to download the file content (as opposed to the file metadata).

Documentation: https://developers.google.com/drive/v3/reference/files/get


var os = require('os');
if (os.platform() == 'win32') {  
    var chilkat = require('chilkat_node6_win32'); 
} else if (os.platform() == 'linux') {
    if (os.arch() == 'arm') {
        var chilkat = require('chilkat_node6_arm');
    } else if (os.arch() == 'x86') {
        var chilkat = require('chilkat_node6_linux32');
    } else {
        var chilkat = require('chilkat_node6_linux64');
    }
} else if (os.platform() == 'darwin') {
    var chilkat = require('chilkat_node6_macosx');
}

function chilkatExample() {

    var rest = new chilkat.Rest();
    var success;

    //   Provide a previously obtained OAuth2 access token.
    var oauth2 = new chilkat.OAuth2();
    oauth2.AccessToken = "OAUTH2_ACCESS_TOKEN";
    rest.SetAuthOAuth2(oauth2);

    success = rest.Connect("www.googleapis.com",443,true,true);
    if (success !== true) {
        console.log(rest.LastErrorText);
        return;
    }

    rest.AddQueryParam("includeTeamDriveItems","true");
    rest.AddQueryParam("supportsTeamDrives","true");
    rest.AddQueryParam("alt","media");

    //  First send the HTTP request.
    success = rest.SendReqNoBody("GET","/drive/v3/files/1R_70heIyzIAu1_u0prXbYcaIiJRVkgBl");
    if (success !== true) {
        console.log(rest.LastErrorText);
        return;
    }

    //  Read the response header.  If the response status code is success, stream to the file.
    //  Otherwise receive the error response text.
    var statusCode = rest.ReadResponseHeader();
    if (statusCode < 0) {
        console.log(rest.LastErrorText);
        return;
    }

    if (statusCode !== 200) {
        console.log("Received error response code: " + statusCode);
        //  Read the error response body.
        var sbErrResponse = new chilkat.StringBuilder();
        success = rest.ReadRespSb(sbErrResponse);
        if (success !== true) {
            console.log(rest.LastErrorText);
            return;
        }

        console.log("Error response:" + sbErrResponse.GetAsString());
        return;
    }

    //  Stream the response body to the output file.
    var respBodyStream = new chilkat.Stream();
    respBodyStream.SinkFile = "/someDirectory/penguins.jpg";
    success = rest.ReadRespBodyStream(respBodyStream,true);
    if (success !== true) {
        console.log(rest.LastErrorText);
        return;
    }

    console.log("Example Completed.");

}

chilkatExample();