import fetch from 'node-fetch';
import * as fs from 'fs';
class NextCloudClient {
private nextCloudUrl: string;
private username: string;
private password: string;
constructor(nextCloudUrl: string, username: string, password: string) {
this.nextCloudUrl = nextCloudUrl;
this.username = username;
this.password = password;
}
private getAuthHeader(): string {
return 'Basic ' + Buffer.from(this.username + ':' + this.password).toString('base64');
}
public async download(filePath: string, destination: string): Promise<void> {
const url = `${this.nextCloudUrl}/remote.php/dav/files/${this.username}${filePath}`;
const response = await fetch(url, {
headers: {
'Authorization': this.getAuthHeader()
}
});
if (!response.ok) {
throw new Error(`Error: ${response.status}`);
}
if (response.body) {
const fileStream = fs.createWriteStream(destination);
response.body.pipe(fileStream);
return new Promise((resolve, reject) => {
fileStream.on('finish', () => {
console.log('File downloaded successfully.');
resolve();
});
fileStream.on('error', reject);
});
} else {
console.log('No response body to download.');
}
}
}
// Usage
const client = new NextCloudClient('http://localhost:8081', 'user', '******');
client.download('/Readme.md', './downloaded_file.txt').catch(console.error);