1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaScriptでNextCloudからファイルをダウンロードする方法

Last updated at Posted at 2023-11-28
import fetch from 'node-fetch';
import * as fs from 'fs';

const nextCloudUrl = 'http://localhost:8081';
const username = 'username';
const password = '******';
const filePath = '/Readme.md';

const download = async () => {
  const url = `${nextCloudUrl}/remote.php/dav/files/${username}${filePath}`;
  const response = await fetch(url, {
    headers: {
      'Authorization': 'Basic ' + Buffer.from(username + ':' + password).toString('base64')
    }
  });

  if (!response.ok) {
    throw new Error(`Error: ${response.status}`);
  }

  if (response.body) {
    const fileStream = fs.createWriteStream('./downloaded_file.txt');
    response.body.pipe(fileStream);
    fileStream.on('finish', () => {
      console.log('File downloaded successfully.');
    });
  } else {
    console.log('No response body to download.');
  }
};

download().catch(error => console.error(error));

クラス版

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);

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?