How to use tar - 10 common examples

To help you get started, we’ve selected a few tar examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ioBroker / ioBroker.js-controller / lib / backup.js View on Github external
name = name.replace(/\\/g, '/');
        if (name.indexOf('/') == -1) {
            name = getBackupDir() + name;
            var regEx = new RegExp('_backup' + tools.appName, 'i');
            if (!regEx.test(name)) name += '_backup' + tools.appName;
            if (!name.match(/\.tar\.gz$/i)) name += '.tar.gz';
        }
        if (!fs.existsSync(name)) {
            console.log('Cannot find ' + name);
            processExit(11);
        }
        var TARgz = require('tar.gz');
        if (fs.existsSync(__dirname + '/../tmp/backup/backup.json')) fs.unlinkSync(__dirname + '/../tmp/backup/backup.json');

        new TARgz().extract(name, __dirname + '/../tmp', function (err) {
            if (err) {
                console.log('Cannot extract from file "' + name + '"');
                processExit(9);
            }
            if (!fs.existsSync(__dirname + '/../tmp/backup/backup.json')) {
                console.log('Cannot find extracted file from file /../tmp/backup/backup.json"');
                processExit(9);
            }
            // Stop controller
            var daemon = require('daemonize2').setup({
                main:       '../controller.js',
                name:       tools.appName + ' controller',
                pidfile:    __dirname + '/' + tools.appName + '.pid',
                cwd:        '../',
                stopTimeout: 1000
            });
github s-panferov / tygen / packages / docscript-react / ignore / cli / publish.ts View on Github external
export function handler(argv: PublishCommand) {
	let manifest = resolveManifestSync()
	let stream = temp.createWriteStream()

	console.log('Writing an archive...')

	fstream
		.Reader({ path: argv.docDir, type: 'Directory' }) /* Read the source directory */
		.pipe(tar.Pack()) /* Convert the directory to a .tar file */
		.pipe(zlib.Gzip()) /* Compress the .tar file */
		.pipe(stream)
		.on('finish', () => {
			console.log('Pushing the archive...')
			let readStream = fs.createReadStream(stream.path)
			let formData = {
				archive: {
					value: readStream,
					options: {
						filename: 'archive.tar.gz',
						contentType: 'application/json charset=utf-8'
					}
				},
				manifest: JSON.stringify(manifest)
			}
github imodeljs / imodeljs / tools / webpack / bin / buildIModelJsModule.js View on Github external
// prepare the digital signature operation
        if (signer) {
            if (this._detail > 3)
                console.log("Calculating signature of plugin resources");
            const signatureFile = path.resolve(buildDir, SIGNATURE_FILENAME);
            const signResult = signer.createSignatureFile(buildDir, fileList, signatureFile);
            if (signResult instanceof Result)
                return Promise.resolve(signResult);
            fileList.push(SIGNATURE_FILENAME);
        }
        if (this._detail > 3)
            console.log("Creating tar file for plugin", subModule.bundleName);
        Utils.makeDirectoryNoError(tarDirectory);
        const tarFile = path.resolve(tarDirectory, subModule.bundleName.concat(".plugin.tar"));
        try {
            await tar.create({ cwd: buildDir, gzip: false, file: tarFile, follow: true }, fileList);
        }
        catch (error) {
            return Promise.resolve(new Result(`Build Plugin ${subModule.bundleName}`, 1, error, "Creating tar file"));
        }
        /* ----------- This is relevant only for the BrowserLocalPluginLoader, which is not currently used.
        // for debugging, put the development version 'bundleName'.js and 'bundlename'.js.map into the same directory as the tar file, and we will preferentially load that.
        const devVersionSource = path.resolve(devCompileOutput, manifest.devPlugin);
        const devVersionDest = path.resolve(outputPath, manifest.devPlugin);
        Utils.symlinkOrCopyModuleFile(devVersionSource, devVersionDest, this._alwaysCopy, this._detail);
           ----------- */
        if (signer) {
            if (this._detail > 3)
                console.log("Verifying signature of plugin tar file");
            // create an output directory, into which we will untar the tar file we just created.
            const verifyResult = await signer.verifySignature(tarFile, subModule, this._detail);
            if (verifyResult)
github expo / expo-cli / packages / xdl / src / Diagnostics.js View on Github external
// remove access token
  try {
    let settingsJsonFile = new JsonFile(path.join(tempDir, UserSettings.SETTINGS_FILE_NAME));
    let settingsJson = await settingsJsonFile.readAsync();
    for (let key of ['accessToken', 'auth', 'uuid', 'sendTo']) {
      if (settingsJson[key]) {
        settingsJson[key] = 'redacted';
      }
    }
    await settingsJsonFile.writeAsync(settingsJson);
  } catch (e) {
    console.error(e);
  }

  // compress
  await tar.create({ file: archivePath, gzip: true, cwd: Env.home() }, [
    path.relative(Env.home(), tempDir),
  ]);
  rimraf.sync(tempDir);

  // upload
  let formData = new FormData();
  formData.append('archive', fs.createReadStream(archivePath));

  let response = await Api.callMethodAsync('uploadDiagnostics', [{}], 'put', null, { formData });
  return response.url;
}
github imodeljs / imodeljs / tools / webpack / modules / buildIModelJsModule.ts View on Github external
console.log("Calculating signature of plugin resources");
      const signatureFile = path.resolve(buildDir, SIGNATURE_FILENAME);
      const signResult: Result | undefined = signer.createSignatureFile(buildDir, fileList, signatureFile);

      if (signResult instanceof Result)
        return Promise.resolve(signResult);

      fileList.push(SIGNATURE_FILENAME);
    }

    if (this._detail > 3)
      console.log("Creating tar file for plugin", subModule.bundleName);
    Utils.makeDirectoryNoError(tarDirectory);
    const tarFile = path.resolve(tarDirectory, subModule.bundleName.concat(".plugin.tar"));
    try {
      await tar.create({ cwd: buildDir, gzip: false, file: tarFile, follow: true }, fileList);
    } catch (error) {
      return Promise.resolve(new Result(`Build Plugin ${subModule.bundleName}`, 1, error, "Creating tar file"));
    }

    /* ----------- This is relevant only for the BrowserLocalPluginLoader, which is not currently used.
    // for debugging, put the development version 'bundleName'.js and 'bundlename'.js.map into the same directory as the tar file, and we will preferentially load that.
    const devVersionSource = path.resolve(devCompileOutput, manifest.devPlugin);
    const devVersionDest = path.resolve(outputPath, manifest.devPlugin);
    Utils.symlinkOrCopyModuleFile(devVersionSource, devVersionDest, this._alwaysCopy, this._detail);
       ----------- */

    if (signer) {
      if (this._detail > 3)
        console.log("Verifying signature of plugin tar file");

      // create an output directory, into which we will untar the tar file we just created.
github arterli / CmsWing / src / admin / controller / database.js View on Github external
targzAction() {
        // Streams
        if (this.isGet()) {
            let paths = think.RESOURCE_PATH;
            let path = "/backup/";
            let dir = paths + path + this.get("dir");
            let tar = paths + path + this.get("dir") + ".tar.gz"
            if (!think.isFile(tar)) {
                //var read = targz().createReadStream(dir);
                //var parse = fs.createWriteStream(tar);
                //read.pipe(parse);
                let self = this;
                targz().compress(dir, tar)
                    .then(function () {
                        self.success({'name': "tar", 'url': self.get("dir")})
                    })
                    .catch(function (err) {
                        console.log('Something is wrong ', err.stack);
                    });

            } else {
                this.success({'name': "download", 'url': this.get("dir")})
            }
        } else if (this.isPost()) {
            let paths = think.RESOURCE_PATH;
            let path = "/backup/";
            let tar = paths + path + this.post("name") + ".tar.gz"
            this.download(tar);
        }
github alibaba / ice / tools / iceworks / app / main / scaffolder / lib / utils.js View on Github external
})
    );
    req
      .on('progress', (state) => {
        progressFunc(state);
      })
      .on('error', (error) => {
        error.name = 'download-tarball-error';
        error.data = {
          url: tarballURL,
        };
        logger.error(error);
        reject(error);
      })
      .pipe(zlib.Unzip()) // eslint-disable-line
      .pipe(tar.Parse()) // eslint-disable-line
      .on('entry', (entry) => {
        if (!/src|mock\//.test(entry.path)) {
          return;
        }

        const isMockFiles = entry.path.indexOf('mock/') !== -1;

        let destPath = ''; // 生成文件的路径
        if (isMockFiles) {
          destPath = path.join(
            clientPath,
            entry.path.replace(/^package\//, '')
          );
        } else {
          const realPath = entry.path
            .replace(/^package\//, '')
github thlorenz / irish-pub / index.js View on Github external
exec('npm pack ' + root, function (err, stdout, stderr) {
    if (err) return out.emit('error', 'Failed to pack archive: ' + err);

    // npm logs created filename on stdout
    var tarFile = path.join(process.cwd(), stdout.trim().split(/\n+/).pop());

    fs.createReadStream(tarFile)
      .on('error', out.emit.bind(out, 'error'))
      .pipe(zlib.createGunzip())
      .on('error', out.emit.bind(out, 'error'))
      .pipe(tar.Parse())
      .on('error', out.emit.bind(out, 'error'))
      .on('entry', function (e) {
        out.write(e.path.replace(/^package\//, '') + '\n');
      })
      .on('end', function () {
        fs.unlink(tarFile, function (err) {
          if (err) return out.emit(err);
          out.emit('end')
        })
      })
  })
}
github alanhoff / node-tar.gz / index.js View on Github external
TarGz.prototype.createParseStream = function() {
  var stream1 = zlib.createGunzip(this._options.zlib);
  var stream2 = tar.Parse();

  this._bubble(stream1, stream2);

  // Capture the entry event
  stream2.on('entry', function(entry) {
    stream1.emit('entry', entry);
  });

  stream1.pipe(stream2);
  return stream1;
};
github deltachat / deltachat-node / scripts / prebuildify.js View on Github external
function bundle () {
  // FIXME. Temporary fix so Jenkins which is faster can upload
  // binaries. Travis uses deploy functionality in .travis.yml and
  // not using the ghreleases module (which seems to fail if there
  // are already binaries uploaded)
  if (process.env.TRAVIS === 'true') return

  const prebuilds = `${process.platform}-${process.arch}`
  const file = `v${pkg.version}-${process.platform}-${process.arch}.tar.gz`
  const cwd = path.join(process.cwd(), 'prebuilds')
  tar.c({ file, cwd, gzip: true }, [ prebuilds ], err => {
    if (err) exit(err)
    uploadToRelease(path.resolve(__dirname, '..', file))
  })
}