Created
January 2, 2018 20:34
-
-
Save allenmichael/bec4796555efb914baab1df1743bd958 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const box = require('box-node-sdk'); | |
const fs = require('fs'); | |
const util = require('util'); | |
const path = require('path'); | |
let configFile = fs.readFileSync('config.json'); | |
configFile = JSON.parse(configFile); | |
let session = box.getPreconfiguredInstance(configFile); | |
let client = session.getAppAuthClient("enterprise"); | |
client._useIterators = true; | |
let folderId = "43491738095"; | |
let folderName; | |
let localFolderPath; | |
client.folders.get(folderId, null) | |
.then((folderInfo) => { | |
folderName = folderInfo.name; | |
return client.folders.getItems(folderId, { limit: 1000 }); | |
}) | |
.then((folderItemsIterator) => { | |
return autoPage(folderItemsIterator); | |
}) | |
.then((folderItems) => { | |
console.log(folderName); | |
console.log(folderItems.length); | |
let files = folderItems.filter((item) => { | |
return item.type === "file"; | |
}); | |
console.log(files); | |
localFolderPath = createLocalFolder(folderName); | |
let downloadPromises = []; | |
files.forEach((file) => { | |
downloadPromises.push(client.files.getReadStream(file.id, null) | |
.then((stream) => { | |
let output = fs.createWriteStream(path.join(localFolderPath, file.name)); | |
stream.pipe(output); | |
})); | |
}); | |
return Promise.all(downloadPromises); | |
}) | |
.then(() => { | |
console.log("Downloaded all files..."); | |
console.log(fs.readdirSync(localFolderPath)); | |
}); | |
function createLocalFolder(folderName) { | |
let localFolderName = path.join(__dirname, folderName); | |
try { | |
fs.mkdirSync(localFolderName); | |
} catch (e) { | |
if (e.code === "EEXIST") { | |
resetLocalFolder(localFolderName); | |
fs.mkdirSync(localFolderName); | |
} else { | |
throw e; | |
} | |
} | |
return localFolderName; | |
} | |
function resetLocalFolder(localFolderName) { | |
if (fs.existsSync(localFolderName)) { | |
fs.readdirSync(localFolderName).forEach((localFileName) => { | |
console.log(localFileName); | |
fs.unlinkSync(path.join(localFolderName, localFileName)); | |
}); | |
fs.rmdirSync(localFolderName); | |
} | |
} | |
function autoPage(iterator) { | |
let collection = []; | |
let moveToNextItem = () => { | |
return iterator.next() | |
.then((item) => { | |
if (item.value) { | |
collection.push(item.value); | |
} | |
if (item.done !== true) { | |
return moveToNextItem(); | |
} else { | |
return collection; | |
} | |
}) | |
} | |
return moveToNextItem(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment