Skip to content
Merged
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
3 changes: 0 additions & 3 deletions .eslintignore

This file was deleted.

7 changes: 4 additions & 3 deletions examples/download.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import fs from 'fs';
import fs from 'node:fs';

import { download } from '../index';
import { download } from '../index.js';

const { API_TOKEN = '' } = process.env;
const fileToSave = fs.createWriteStream('./Mountains.jpg');

download(API_TOKEN, 'disk:/Горы.jpg', (download) => download.pipe(fileToSave));
const stream = await download(API_TOKEN, 'disk:/Горы.jpg');
stream.pipe(fileToSave);
25 changes: 15 additions & 10 deletions examples/upload.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,20 @@
import fs from 'fs';
import path from 'path';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

import { upload } from '../index';
import { upload } from '../index.js';

Comment thread
greptile-apps[bot] marked this conversation as resolved.
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const { API_TOKEN = '' } = process.env;
const fileToUpload = fs.createReadStream(path.join(__dirname, 'upload.js'));

upload(
API_TOKEN,
'disk:/Приложения/ya-disk-api/upload.js',
true,
(stream) => fileToUpload.pipe(stream),
(err) => process.stderr.write(err)
);
try {
const stream = await upload(
API_TOKEN,
'disk:/Приложения/ya-disk-api/upload.js',
true
);
fileToUpload.pipe(stream);
} catch (err) {
process.stderr.write(err);
}
77 changes: 31 additions & 46 deletions features/upload-and-download-file.feature.js
Original file line number Diff line number Diff line change
@@ -1,71 +1,56 @@
const fs = require('fs');
const https = require('https');
const path = require('path');
const assert = require('node:assert/strict');
const { after, before, describe, it } = require('node:test');
import fs from 'node:fs';
import https from 'node:https';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import assert from 'node:assert/strict';
import { after, before, describe, it } from 'node:test';

const { meta, resources } = require('ya-disk');
import { meta, resources } from 'ya-disk';

const { API_TOKEN } = process.env;
const { upload: uploadStream, download: downloadStream } = require('../index');
const { upload: uploadStream, download: downloadStream } =
await import('../index.js');

const shouldRun = API_TOKEN && process.env.GITHUB_ACTOR !== 'dependabot[bot]';
const describeOrSkip = shouldRun ? describe : describe.skip;

const yaDiskPath = fileURLToPath(import.meta.resolve('ya-disk'));
const localFileName = path.resolve(
require.resolve('ya-disk').split('node_modules/')[0],
yaDiskPath.split('node_modules/')[0],
'package.json'
);
const localReadStream = fs.createReadStream(localFileName);
const { size: localFileSize } = fs.statSync(localFileName);
const remoteFileName = `package_${Math.round(Math.random() * 100)}.json`;
const remoteFilePath = `disk:/${remoteFileName}`;

function getRemoteFileSize(remoteFile) {
return new Promise((resolve, reject) => {
meta.get(
API_TOKEN,
remoteFile,
{ fields: 'name,size' },
({ size }) => resolve(size),
reject
);
async function getRemoteFileSize(remoteFile) {
const { size } = await meta.get(API_TOKEN, remoteFile, {
fields: 'name,size'
});
return size;
}

function uploadFile(token, filePath, stream) {
return new Promise((resolve, reject) => {
uploadStream(
token,
filePath,
true,
(writeStream) => {
writeStream.on('finish', resolve);
stream.pipe(writeStream);
},
reject
);
});
async function uploadFile(token, filePath, stream) {
const writeStream = await uploadStream(token, filePath, true);
const { promise, resolve, reject } = Promise.withResolvers();
writeStream.on('finish', resolve);
writeStream.on('error', reject);
stream.pipe(writeStream);
return promise;
}

function downloadFile(token, filePath, writeStream) {
return new Promise((resolve, reject) => {
downloadStream(
token,
filePath,
(readStream) => {
writeStream.on('finish', resolve);
readStream.pipe(writeStream);
},
reject
);
});
async function downloadFile(token, filePath, writeStream) {
const readStream = await downloadStream(token, filePath);
const { promise, resolve, reject } = Promise.withResolvers();
writeStream.on('finish', resolve);
writeStream.on('error', reject);
readStream.pipe(writeStream);
return promise;
}

function removeFile(token, filePath) {
return new Promise((resolve) => {
resources.remove(token, filePath, true, resolve, resolve);
});
async function removeFile(token, filePath) {
await resources.remove(token, filePath, true);
}

let localWriteStream;
Expand Down
6 changes: 2 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,2 @@
module.exports = {
upload: require('./lib/upload'),
download: require('./lib/download')
};
export { upload } from './lib/upload.js';
export { download } from './lib/download.js';
20 changes: 8 additions & 12 deletions lib/download.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,14 @@
const { download } = require('ya-disk');
import { download as yaDiskDownload } from 'ya-disk';

const followRedirect = require('./followRedirect');
import { followRedirect } from './followRedirect.js';

/**
* Creates readable stream to download file from the Yadex.Disk
* Creates readable stream to download file from Yandex.Disk
* @param {string} token OAuth-token
* @param {string} file Path+filename on the storage
* @param {function} [onReady] Callback to be called after stream being ready
* @param {function} [onError] Callback to be called in case of any error
* @returns {Promise<import('stream').Readable>}
*/
module.exports = (token, file, onReady, onError) =>
download.link(
token,
file,
({ href, method }) => followRedirect(href, method, (req) => onReady(req)),
onError
);
export async function download(token, file) {
const { href, method } = await yaDiskDownload.link(token, file);
return followRedirect(href, method);
}
37 changes: 20 additions & 17 deletions lib/followRedirect.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,23 @@
const https = require('https');
const { parse: urlParse } = require('url');
import https from 'node:https';

const followRedirect = (url, method = 'GET', onReady) => {
const req = https.request(
Object.assign({}, urlParse(url), { method }),
(res) => {
if (res.statusCode >= 300 && res.statusCode < 400) {
res.destroy();
followRedirect(res.headers.location, method, onReady);
} else if (res.statusCode === 200 && typeof onReady === 'function') {
onReady(res);
}
}
);
export function followRedirect(url, method = 'GET') {
return new Promise((resolve, reject) => {
const makeRequest = (url) => {
const req = https.request(url, { method }, (res) => {
if (res.statusCode >= 300 && res.statusCode < 400) {
res.destroy();
makeRequest(res.headers.location);
} else if (res.statusCode === 200) {
resolve(res);
} else {
reject(new Error(`Unexpected status code: ${res.statusCode}`));
}
});

req.end();
};
req.on('error', reject);
req.end();
};

module.exports = followRedirect;
makeRequest(url);
});
}
23 changes: 8 additions & 15 deletions lib/upload.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,14 @@
const https = require('https');
const { upload } = require('ya-disk');
const { parse: urlParse } = require('url');
import https from 'node:https';
import { upload as yaDiskUpload } from 'ya-disk';

/**
* Create writable stream for uploading file to Yandex.Disk
* Creates writable stream for uploading file to Yandex.Disk
* @param {string} token OAuth-token
* @param {string} file Path+filename on the storage
* @param {boolean} [overwrite=true] Overwrite existing file
* @param {function} onReady Callback to be called after stream being ready
* @param {function} onError Callback to be called in case of any error
* @returns {Promise<import('stream').Writable>}
*/
module.exports = (token, file, overwrite = true, onReady, onError) =>
upload.link(
token,
file,
overwrite,
({ href, method }) =>
onReady(https.request(Object.assign({}, urlParse(href), { method }))),
onError
);
export async function upload(token, file, overwrite = true) {
const { href, method } = await yaDiskUpload.link(token, file, overwrite);
return https.request(href, { method });
}
Loading