Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Created August 17, 2017 00:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tanaikech/38b536923b1765da052c21aab093649d to your computer and use it in GitHub Desktop.
Save tanaikech/38b536923b1765da052c21aab093649d to your computer and use it in GitHub Desktop.
Downloading Files Under Specific Folder using Node.js

Downloading Files Under Specific Folder using Node.js

This sample script is for downloading files under a specific folder using Node.js. It can download files with Google Docs and others.

This sample supposes as follows. So please confirm it.

  • quickstart is used and default quickstart works fine.

In order to use this sample, please carry out as follows.

  1. Replace listFiles() of the default quickstart to this sample.
  2. Set folderid. This script can retrieve files in the folder with folderid.
  3. Delete drive-nodejs-quickstart.json. I think that there is the file at .credentials in your home directory.
  4. Change the SCOPE from var SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly']; to var SCOPES = ['https://www.googleapis.com/auth/drive.readonly'];.
  5. Run script, retrieve the code and authorize.

Script :

function listFiles(auth) {
  var folderid = "### folder ID ###"; // Folder ID. This script downloads files in the folder with this folder ID.
  var outputExtension = "pdf"; // Extension of output file. This is adapted to only Google Docs.

  var outputMimeType = mime.lookup(outputExtension);
  var service = google.drive('v3');
  service.files.list({
    auth: auth,
    q: "'" + folderid + "' in parents and trashed=false",
    fields: "files(id, name, mimeType)"
  }, function(err, response) {
    if (err) {
      console.log('The API returned an error: ' + err);
      return;
    }
    response.files.forEach(function(e){
      if (e.mimeType.includes("application/vnd.google-apps")) {
        var dlfile = fs.createWriteStream(e.name + "." + outputExtension);
        service.files.export({
          auth: auth,
          fileId: e.id,
          mimeType: outputMimeType
        }).on('end', function() {
          console.log("'%s' was downloaded as %s.", e.name, outputExtension);
        }).on('error', function(err) {
          console.error(err);
          return process.exit();
        }).pipe(dlfile);
      } else {
        var dlfile = fs.createWriteStream(e.name);
        service.files.get({
          auth: auth,
          fileId: e.id,
          alt: 'media'
        }).on('end', function() {
          console.log("'%s' was downloaded as %s.", e.name, mime.extension(e.mimeType));
        }).on('error', function(err) {
          console.error(err);
          return process.exit();
        }).pipe(dlfile);
      }
    });
  });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment