Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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<void>}
*/
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
Expand Down
40 changes: 40 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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}`)
})
Expand Down