diff --git a/lib/index.js b/lib/index.js index bb56f6d..8139251 100644 --- a/lib/index.js +++ b/lib/index.js @@ -467,6 +467,35 @@ class Sharepoint { logAxiosError(this.debug, err, 'Unable to delete file') } } + + /** + * Download the specified file + * @param sourcePath path to the file to download + * @param targetPath path to where to download the file to + * @returns {Promise} + */ + async downloadFile (sourcePath, targetPath) { + try { + checkHeaders(this.accessToken) + + const file = await axios.get( + `${this.siteUrl}/_layouts/15/download.aspx?sourceUrl=${this.encodedBaseUrl}${encodeURIComponent(sourcePath)}`, + { + headers: { + Authorization: `Bearer ${this.accessToken}`, + Accept: 'application/json;odata=verbose' + }, + responseType: 'stream' + } + ) + + const fileName = sourcePath.split('/').reverse()[0] + const fileStream = fs.createWriteStream(`${targetPath}/${fileName}`) + await file.data.pipe(fileStream) + } catch (err) { + logAxiosError(this.debug, err, 'Unable to download file') + } + } } // based on https://axios-http.com/docs/handling_errors diff --git a/test/test.js b/test/test.js index 2ead750..8e40125 100644 --- a/test/test.js +++ b/test/test.js @@ -370,6 +370,46 @@ describe('tests', function () { }) }) + it('download text file', async () => { + const targetPath = path.resolve(__dirname, 'output') + + // Ensure target path exists + if (!fs.existsSync(targetPath)) { + fs.mkdirSync(targetPath) + } + + // Download file to target path + await sharepoint.downloadFile( + `${process.env.SHAREPOINT_TESTS_DIR_PATH}/${FOLDER_NAME1}/${FILE_NAME1}`, + targetPath + ) + + // Check downloaded file content + const expectedFile = await fs.readFileSync(path.join(__dirname, 'fixtures', 'Test.txt'), 'utf-8') + const downloadedFile = await fs.readFileSync(path.join(targetPath, FILE_NAME1), 'utf-8') + expect(downloadedFile).to.eql(expectedFile) + }) + + it('download binary file', async () => { + const targetPath = path.resolve(__dirname, 'output') + + // Ensure target path exists + if (!fs.existsSync(targetPath)) { + fs.mkdirSync(targetPath) + } + + // Download file to target path + await sharepoint.downloadFile( + `${process.env.SHAREPOINT_TESTS_DIR_PATH}/${FOLDER_NAME1}/${BINARY_FILE_FILENAME}`, + targetPath + ) + + // Check downloaded file content + const expectedFile = await fs.readFileSync(path.join(__dirname, 'fixtures', 'Test.png'), 'utf-8') + const downloadedFile = await fs.readFileSync(path.join(targetPath, BINARY_FILE_FILENAME), 'utf-8') + expect(downloadedFile).to.eql(expectedFile) + }) + it('delete folder 1', async () => { await sharepoint.deleteFolder(`${process.env.SHAREPOINT_TESTS_DIR_PATH}/${FOLDER_NAME1}`) })