Skip to content

Instantly share code, notes, and snippets.

@tomasevich
Last active August 3, 2018 09:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomasevich/42d0cba5870efb97165aa02768b5af61 to your computer and use it in GitHub Desktop.
Save tomasevich/42d0cba5870efb97165aa02768b5af61 to your computer and use it in GitHub Desktop.
Download file (archive) from GitHub and unpack (tar.gz)

Loader

Choose your language

MIT License

English

Description

This is a simple script for NodeJS, which was developed to download releases from the site GitHub. It allows you to download a file from the repository and unpack it into the desired folder.

Warning: When unpacking the archive .tar.gz the script overwrites the folder (does not update it)!

How to use?

  1. Connect the file loader.js
  2. Create a new object
  3. Configure remote, local and the final path
  4. Run it

Script and example below!

From the author

I hope you find this script useful. I will be glad to respond to your comments (preferably in Russian or English)!

Русский

Описание

Это простой скрипт для NodeJS, который был разработан для загрузки релизов с сайта GitHub. Он позволяет загружать файл из репозитория и распаковывать его в нужную папку.

Предупреждение: При распаковке архива .tar.gz скрипт перезаписывает папку (не обновляет ее)!

Как использовать?

  1. Подключаем файл loader.js
  2. Создаем новый объект
  3. Настраиваем удаленный, локальный и конечный путь
  4. Запускаем

Скрипт и пример ниже!

От автора

Надеюсь, вам пригодится данный скрипт. Буду рад ответить на ваши комментарии (желательно на русском или английском языке)!

Deutsch

Beschreibung

Dies ist ein einfaches Skript für NodeJS, das entwickelt wurde, um Releases von der Site GitHub herunterzuladen. Sie können eine Datei aus dem Repository herunterladen und in den gewünschten Ordner entpacken.

Warnung: Beim Entpacken des Archivs .tar.gz überschreibt das Skript den Ordner (wird nicht aktualisiert)!

Wie benutze ich?

  1. Verbinde die Datei loader.js
  2. Erstellen Sie ein neues Objekt
  3. Konfigurieren Sie remote, local und den endgültigen Pfad
  4. Wir beginnen

Skript und Beispiel unten!

Vom Autor

Ich hoffe, Sie finden dieses Skript nützlich. Ich werde gerne auf Ihre Kommentare antworten (vorzugsweise auf Russisch oder Englisch)!

Français

Description

Ceci est un script simple pour NodeJS, qui a été développé pour télécharger les versions du site GitHub. Il vous permet de télécharger un fichier depuis le référentiel et de le décompresser dans le dossier souhaité.

Avertissement: Lors du déballage de l'archive .tar.gz, le script écrase le dossier (ne le met pas à jour)!

Comment utiliser?

  1. Connectez le fichier loader.js
  2. Créez un nouvel objet
  3. Configurez remote, local et le chemin final
  4. Nous commençons

Script et exemple ci-dessous!

De l'auteur

J'espère que vous trouvez ce script utile. Je serai heureux de répondre à vos commentaires (de préférence en russe ou en anglais)!

Español

Descripción

Este es un script simple para NodeJS, que fue desarrollado para descargar versiones del sitio GitHub. Le permite descargar un archivo del repositorio y descomprimirlo en la carpeta deseada.

Advertencia: Al desempacar el archivo .tar.gz, el script sobrescribe la carpeta (¡no la actualiza)!

¿Cómo usar?

  1. Conecte el archivo loader.js
  2. Crea un nuevo objeto
  3. Configure remoto, local y la ruta final
  4. Comenzamos

Script y example a continuación.

Del autor

Espero que este script te sea útil. Estaré encantado de responder a sus comentarios (preferiblemente en ruso o inglés)!

日本

説明

これは、サイト** GitHubからリリースをダウンロードするために開発されたNodeJS**の簡単なスクリプトです。リポジトリからファイルをダウンロードし、目的のフォルダに展開することができます。

警告アーカイブ .tar.gzをアンパックすると、スクリプトはフォルダを上書きします(更新しません)!

どのように使いますか?

  1. ファイル loader.jsを接続します。
  2. 新しいオブジェクトを作成する
  3. リモートローカル最終パスを設定する
  4. 始めましょう

Script and example below!

著者から

このスクリプトが役立つことを願っています。私はあなたのコメント(好ましくはロシア語または英語)にお答えできてうれしいです!

Script

'use strict'

const path = require ('path');
const url = require ('url');
const http = require ('http');
const https = require ('https');
const { createReadStream, createWriteStream } = require ('fs');
const unpack = require ('tar-pack').unpack;
const chalk = require ('chalk');

var log = console.log;

function loader (unpackage) {
	this.unpackage = unpackage;
	log (`${chalk.cyan ('Init')}`);
};

loader.prototype.file = {
	write: {},
	ready: false,
	bytes: 0
};
loader.prototype.contentLength = 0;
loader.prototype.remote = '';
loader.prototype.local = '';
loader.prototype.unpack = '';
loader.prototype.redirect = false;
loader.prototype.percent = 0;
loader.prototype.transport = {};
loader.prototype.port = 0;

loader.prototype.set = function (type, name) {
	log (`${chalk.blue ('Set:')} ${chalk.black (type)} ${chalk.grey (name)}`);
	this[type] = name;
};

loader.prototype.run = function () {
	log (`${chalk.cyan ('Start')}`);
	this.download (this.remote, this.local, 0);
};

loader.prototype.download = function (remote, local) {
	log (`${chalk.cyan ('Request:')} ${chalk.grey (remote)}`);
	var __ = this;
	if (remote.indexOf ('https') != -1) {
		__.port = 443;
		__.transport = https;
	} else {
		__.port = 80;
		__.transport = http;
	}
	var request = __.transport.get ({
		host: url.parse (remote).hostname,
		port: __.port,
		path: url.parse (remote).pathname
	}, function (response) {
		switch (response.statusCode) {
			case 200:
				log (`${chalk.cyan ('Response:')} ${chalk.green (response.statusCode)}`);
				__.contentLength = response.headers['content-length'];
			break;
			case 302:
				log (`${chalk.cyan ('Response:')} ${chalk.grey (response.statusCode)}`);
				__.download (response.headers.location, local);
				return;
			break;
			case 404:
				log (`${chalk.cyan ('Response:')} ${chalk.orange (response.statusCode)}`);
			default:
				log (`${chalk.cyan ('Response:')} ${chalk.red (response.statusCode)}`);
				request.abort ();
				return;
		}
		response.on ('data', function (chunk) {
			log (`${chalk.cyan ('Download')}`);
			if(!__.file.ready) {
				__.file.write = createWriteStream (local);
				__.file.ready = true;
			}
			__.file.write.write (chunk);
			__.file.bytes += chunk.length;
			__.percent = parseInt ((__.file.bytes / __.contentLength) * 100);
			log (`${chalk.cyan ('Percent:')} ${chalk.green (__.percent)}${chalk.green ('%')}`);
		});
		response.on ('end', function () {
			log (`${chalk.green ('Done')}`);
			__.file.write.end (function (argument) {
				if (__.unpackage) {
					createReadStream (local).pipe (unpack (__.unpack, function (err) {
						log (`${chalk.cyan ('Unpack')} ${chalk.grey (__.unpack)}`);
						if (err) {
							log (`${chalk.red ('Error:')} ${chalk.red (err)}`);
						} else {
							log (`${chalk.green ('Finish')}`);
						}
					}));
				}
			});
		});

	});
	request.on ('error', function (err) {
		log (`${chalk.red ('Error:')} ${chalk.red (err.message)}`);
	});
};

module.exports = loader;

Example

'use strict'
/* 1 */
const loader = require ('./loader');
/* 2 */
var load = new loader (true);
	/* 3 */
	load.set ('remote', 'https://github.com/rateljs/cms/archive/v0.0.0.tar.gz');
	load.set ('local', './application/v0.0.0.tar.gz');
	load.set ('unpack', './application/v0.0.0/');
	/* 4 */
	load.run ();

Example 2

'use strict'
/* 1 */
const loader = require ('./loader');
/* 2 */
var load = new loader (false);
	/* 3 */
	load.set ('remote', 'https://github.com/rateljs/cms/archive/v0.0.0.tar.gz');
	load.set ('local', './application/v0.0.0.tar.gz');
	/* 4 */
	load.run ();

Result

2018-08-03 9 22 16

MIT License

Copyright (c) 2018 Vyacheslav Tomasevich vyacheslav.tomasevich@gmail.com

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment