Best JavaScript code snippet using appium-xcuitest-driver
helpers.js
Source:helpers.js  
...118    const tmpZipRoot = path.resolve(tmpRoot, 'apk');119    await zip.extractAllTo(apkPath, tmpZipRoot);120    await fs.rimraf(path.resolve(tmpZipRoot, metaInfFolderName));121    const tmpResultPath = path.resolve(tmpRoot, path.basename(apkPath));122    await zip.toArchive(tmpResultPath, {123      cwd: tmpZipRoot,124    });125    await fs.unlink(apkPath);126    await fs.mv(tmpResultPath, apkPath);127    return true;128  } finally {129    await fs.rimraf(tmpRoot);130  }131}132function getIMEListFromOutput (stdout) {133  let engines = [];134  for (let line of stdout.split('\n')) {135    if (line.length > 0 && line[0] !== ' ') {136      // remove newline and trailing colon, and add to the list...performance.js
Source:performance.js  
...74    const zippedReportPath = originalReportPath.replace(`.${DEFAULT_EXT}`, '.zip');75    // This is to prevent possible race conditions, because the archive operation76    // could be pretty time-intensive77    if (!this._archivePromise) {78      this._archivePromise = zip.toArchive(zippedReportPath, {79        cwd: originalReportPath,80      });81    }82    await this._archivePromise;83    this._zippedReportPath = zippedReportPath;84    return this._zippedReportPath;85  }86  isRunning () {87    return !!(this._process?.isRunning);88  }89  async _enforceTermination () {90    if (this._process && this.isRunning()) {91      this._logger.debug('Force-stopping the currently running perf recording');92      try {...zip-e2e-specs.js
Source:zip-e2e-specs.js  
...152      describe('toArchive', function () {153        it('should zip all files into an archive', async function () {154          const testFolder = path.resolve(assetsPath, 'unzipped');155          const dstPath = path.resolve(tmpRoot, 'test.zip');156          await zip.toArchive(dstPath, {157            cwd: testFolder,158          });159          // Unzip the file and test that it has the same contents as the directory that was zipped160          await zip.extractAllTo(dstPath, path.resolve(tmpRoot, 'output'));161          await fs.readFile(path.resolve(tmpRoot, 'output', 'test-dir', 'a.txt'), {162            encoding: 'utf8'163          }).should.eventually.equal('Hello World');164          await fs.readFile(path.resolve(tmpRoot, 'output', 'test-dir', 'b.txt'), {165            encoding: 'utf8'166          }).should.eventually.equal('Foo Bar');167        });168      });169    });170  });...android-manifest.js
Source:android-manifest.js  
...196      await zip.extractAllTo(srcApk, tmpRoot);197      log.debug('Moving manifest');198      await fs.mv(manifest, path.resolve(tmpRoot, manifestName));199      log.debug(`Collecting the destination apk at '${dstApk}'`);200      await zip.toArchive(dstApk, {201        cwd: tmpRoot,202      });203    } finally {204      await fs.rimraf(tmpRoot);205    }206  }207  log.debug(`Manifest insertion into '${dstApk}' is completed`);208};209/**210 * Check whether package manifest contains Internet permissions.211 *212 * @param {string} appPath - The full path to .apk(s) package.213 * @return {boolean} True if the manifest requires Internet access permission.214 */...zip.js
Source:zip.js  
1import B from 'bluebird';2import nodeExtract from 'extract-zip';3import yauzl from 'yauzl';4import archiver from 'archiver';5import { createWriteStream } from 'fs';6import path from 'path';7import { mkdirp } from '../lib/mkdirp';8import stream from 'stream';9import fs from './fs';10const extract = B.promisify(nodeExtract);11const open = B.promisify(yauzl.open);12const ZIP_MAGIC = 'PK';13/**14 * Extract zipfile to a directory15 *16 * @param {string} zipFilePath The full path to the source ZIP file17 * @param {string} destDir The full path to the destination folder18 */19async function extractAllTo (zipFilePath, destDir) {20  return await extract(zipFilePath, {dir: destDir});21}22/**23 * Extract a single zip entry to a directory24 *25 * @param {Streamable} zipFile The source ZIP stream26 * @param {yauzl.ZipEntry} entry The entry instance27 * @param {string} destDir The full path to the destination folder28 */29async function _extractEntryTo (zipFile, entry, destDir) {30  const dstPath = path.resolve(destDir, entry.fileName);31  // Create dest directory if doesn't exist already32  if (/\/$/.test(entry.fileName)) {33    if (!await fs.exists(dstPath)) {34      await mkdirp(dstPath);35    }36    return;37  } else if (!await fs.exists(path.dirname(dstPath))) {38    await mkdirp(path.dirname(dstPath));39  }40  // Create a write stream41  const writeStream = createWriteStream(dstPath, {flags: 'w'});42  const writeStreamPromise = new B((resolve, reject) => {43    writeStream.once('finish', resolve);44    writeStream.once('error', reject);45  });46  // Create zipReadStream and pipe data to the write stream47  // (for some odd reason B.promisify doesn't work on zipfile.openReadStream, it causes an error 'closed')48  const zipReadStream = await new B((resolve, reject) => {49    zipFile.openReadStream(entry, (err, readStream) => err ? reject(err) : resolve(readStream));50  });51  const zipReadStreamPromise = new B((resolve, reject) => {52    zipReadStream.once('end', resolve);53    zipReadStream.once('error', reject);54  });55  zipReadStream.pipe(writeStream);56  // Wait for the zipReadStream and writeStream to end before returning57  return await B.all([58    zipReadStreamPromise,59    writeStreamPromise,60  ]);61}62/**63 * @typedef {Object} ZipEntry64 * @property {yauzl.ZipEntry} entry The actual entry instance65 * @property {function} extractEntryTo An async function, which accepts one parameter.66 * This parameter contains the destination folder path to which this function is going to extract the entry.67 */68/**69 * Get entries for a zip folder70 *71 * @param {string} zipFilePath The full path to the source ZIP file72 * @param {function} onEntry Callback when entry is read.73 * The callback is expected to accept one argument of ZipEntry type.74 * The iteration through the source zip file will bi terminated as soon as75 * the result of this function equals to `false`.76 */77async function readEntries (zipFilePath, onEntry) {78  // Open a zip file and start reading entries79  const zipfile = await open(zipFilePath, {lazyEntries: true});80  const zipReadStreamPromise = new B((resolve, reject) => {81    zipfile.once('end', resolve);82    zipfile.once('error', reject);83    // On each entry, call 'onEntry' and then read the next entry84    zipfile.on('entry', async (entry) => {85      const res = await onEntry({86        entry,87        extractEntryTo: async (destDir) => await _extractEntryTo(zipfile, entry, destDir)88      });89      if (res === false) {90        return zipfile.emit('end');91      }92      zipfile.readEntry();93    });94  });95  zipfile.readEntry();96  // Wait for the entries to finish being iterated through97  return await zipReadStreamPromise;98}99/**100 * Converts contents of local directory to an in-memory .zip buffer101 *102 * @param {string} srcDir The full path to the folder being zipped103 * @returns {Buffer} Zipped content of the source folder as memory buffer104 */105async function toInMemoryZip (srcDir) {106  // Create a writable stream that zip buffers will be streamed to107  const zipBufferArr = [];108  const zipWriteStream = new stream.Writable({109    write: (buffer, encoding, next) => {110      zipBufferArr.push(buffer);111      next();112    },113  });114  const zipWriteStreamPromise = new B((resolve) => {115    // Don't need to do error handling since this writeStream is in-memory and doesn't emit any errors116    zipWriteStream.once('finish', resolve);117  });118  // Zip 'srcDir' and stream it to the above writable stream119  const archive = archiver('zip', {120    zlib: {level: 9}121  });122  const archiveStreamPromise = new B((resolve, reject) => {123    archive.once('finish', resolve);124    archive.once('error', (errStr) => reject(new Error(`Failed to zip directory ${srcDir}: ${errStr}`)));125  });126  archive.directory(srcDir, false);127  archive.pipe(zipWriteStream);128  archive.finalize();129  // Wait for the streams to finish130  await B.all([archiveStreamPromise, zipWriteStreamPromise]);131  // Return the array of zip buffers concatenated into one buffer132  return Buffer.concat(zipBufferArr);133}134/**135 * Verifies whether the given file is a valid ZIP archive136 *137 * @param {string} filePath - Full path to the file138 * @throws {Error} If the file does not exist or is not a valid ZIP archive139 */140async function assertValidZip (filePath) {141  if (!await fs.exists(filePath)) {142    throw new Error(`The file at '${filePath}' does not exist`);143  }144  const {size} = await fs.stat(filePath);145  if (size < 4) {146    throw new Error(`The file at '${filePath}' is too small to be a ZIP archive`);147  }148  const fd = await fs.open(filePath, 'r');149  try {150    const buffer = Buffer.alloc(ZIP_MAGIC.length);151    await fs.read(fd, buffer, 0, ZIP_MAGIC.length, 0);152    const signature = buffer.toString('ascii');153    if (signature !== ZIP_MAGIC) {154      throw new Error(`The file signature '${signature}' of '${filePath}' ` +155        `is not equal to the expected ZIP archive signature '${ZIP_MAGIC}'`);156    }157    return true;158  } finally {159    await fs.close(fd);160  }161}162/**163 * @typedef {Object} ZipCompressionOptions164 * @property {number} level [9] - Compression level in range 0..9165 * (greater numbers mean better compression, but longer processing time)166 */167/**168 * @typedef {Object} ZipSourceOptions169 * @property {!string} pattern ['**\/*'] - GLOB pattern for compression170 * @property {!string} cwd - The source root folder (the parent folder of171 * the destination file by default)172 * @property {?Array<string>} ignore - The list of ignored patterns173 */174/**175 * Creates an archive based on the given glob pattern176 *177 * @param {string} dstPath - The resulting archive path178 * @param {ZipSourceOptions} src - Source options179 * @param {ZipCompressionOptions} opts - Compression options180 * @throws {Error} If there was an error while creating the archive181 */182async function toArchive (dstPath, src = {}, opts = {}) {183  const {184    level = 9,185  } = opts;186  const {187    pattern = '**/*',188    cwd = path.dirname(dstPath),189    ignore = [],190  } = src;191  const archive = archiver('zip', { zlib: { level }});192  const stream = fs.createWriteStream(dstPath);193  return await new B((resolve, reject) => {194    archive195      .glob(pattern, {196        cwd,197        ignore,198      })199      .on('error', reject)200      .pipe(stream);201    stream.on('close', resolve);202    archive.finalize();203  });204}205export { extractAllTo, readEntries, toInMemoryZip, _extractEntryTo,206  assertValidZip, toArchive };...build-webdriveragent.js
Source:build-webdriveragent.js  
...57  await mkdirp(path.resolve(uncompressedDir, 'DerivedData'));58  await fs.rename(wdaPath, path.resolve(uncompressedDir, 'DerivedData', 'WebDriverAgent'));59  // Compress the "uncompressed" bundle as a Zip60  const pathToZip = path.resolve(pathToBundles, `webdriveragent-xcode_${xcodeVersion}.zip`);61  await zip.toArchive(62    pathToZip, {cwd: path.join(rootDir, 'uncompressed')}63  );64  log.info(`Zip bundled at "${pathToZip}"`);65  // Now just zip the .app and place it in the root directory66  // This zip file will be published to NPM67  const wdaAppBundle = 'WebDriverAgentRunner-Runner.app';68  const appBundlePath = path.join(uncompressedDir, 'DerivedData', 'WebDriverAgent',69    'Build', 'Products', 'Debug-iphonesimulator', wdaAppBundle);70  const appBundleZipPath = path.join(rootDir, `${wdaAppBundle}.zip`);71  await fs.rimraf(appBundleZipPath);72  log.info(`Created './${wdaAppBundle}.zip'`);73  await zip.toArchive(appBundleZipPath, {cwd: appBundlePath});74  log.info(`Zip bundled at "${appBundleZipPath}"`);75  // Clean up the uncompressed directory76  await fs.rimraf(uncompressedDir);77}78if (require.main === module) {79  asyncify(buildWebDriverAgent);80}...Using AI Code Generation
1var wd = require('wd');2var assert = require('chai').assert;3var zip = require('appium-xcuitest-driver').zip;4var remoteConfig = {5};6var desired = {7};8var driver = wd.promiseChainRemote(remoteConfig);9driver.init(desired)10  .then(function () {11    return driver.source();12  })13  .then(function (source) {14    console.log(source);15    return driver.quit();16  })17  .catch(function (err) {18    console.log(err);19    return driver.quit();20  })21var wd = require('wd');22var assert = require('chai').assert;23var zip = require('appium-xcuitest-driver').zip;24var remoteConfig = {25};26var desired = {27};28var driver = wd.promiseChainRemote(remoteConfig);29driver.init(desired)30  .then(function () {31    return driver.startRecordingScreen();32  })33  .then(function (base64String) {34    return zip.toInMemoryBase64(base64String);35  })36  .then(function (base64String) {37    console.log(base64String);38    return driver.quit();39  })40  .catch(function (err) {41    console.log(err);42    return driver.quit();43  })44var wd = require('wd');45var assert = require('chai').assert;46var zip = require('appium-xcuitest-driver').zip;47var remoteConfig = {48};49var desired = {Using AI Code Generation
1const path = require('path');2const fs = require('fs');3const AdmZip = require('adm-zip');4const zip = new AdmZip();5zip.addLocalFolder('/Users/xyz/Desktop/abc');6zip.toBuffer();7const zipPath = path.join(__dirname, 'abc.zip');8zip.writeZip(zipPath);9const AdmZip = require('adm-zip');10const zip = new AdmZip('/Users/xyz/Desktop/abc.zip');11zip.extractAllTo('/Users/xyz/Desktop/abc', true);12commands.zip = async function zip (opts = {}) {13  const {14  } = opts;15  const remotePathWithoutFile = path.dirname(remotePath);16  const remoteFileName = path.basename(remotePath);17  const remotePathWithoutFileEscaped = escapeSpace(remotePathWithoutFile);18  const zipFileEscaped = escapeSpace(zipFile);19  await this.createDirectory(remotePathWithoutFileEscaped);20  await this.createArchive(remotePathWithoutFileEscaped, remoteFileName, zipFileEscaped);21  return true;22};23commands.unzip = async function unzip (opts = {}) {24  const {25  } = opts;26  const zipFileEscaped = escapeSpace(zipFile);27  const destinationEscaped = escapeSpace(destination);28  await this.extractArchive(zipFileEscaped, destinationEscaped);29  return true;30};31commands.createArchive = async function createArchive (remotePathWithoutFile, remoteFileName, zipFile) {32  const cmd = `cd '${remotePathWithoutFile}' && zip -r '${zipFile}' '${remoteFileName}'`;33  log.debug(`Creating zip archive with command: ${cmd}`);34  await this.exec(cmd, {timeout: 30000});35};36commands.extractArchive = async function extractArchive (zipFile, destination) {37  const cmd = `unzip '${zipFile}' -d '${destination}'`;38  log.debug(`Extracting zip archive with command: ${cmd}`);39  await this.exec(cmd, {timeout: 30000});40};41module.exports = commands;42function escapeSpace (str) {43  return str.replace(/ /g, '\\ ');44}Using AI Code Generation
1const zip = require('appium-support').zip;2const path = require('path');3const fs = require('fs');4const dirToZip = path.resolve('test');5const zipFile = path.resolve('test.zip');6const unzippedDir = path.resolve('unzipped');7async function main () {8  await zip.toArchive(dirToZip, zipFile);9  await zip.extractAllTo(zipFile, unzippedDir);10  console.log('Done');11}12main();Using AI Code Generation
1var zip = require('node-native-zip');2var archive = new zip();3var path = require('path');4var fs = require('fs');5var files = fs.readdirSync('/Users/bob/Downloads/MyApp.app');6files.forEach(function(file) {7    archive.add(path.join('/Users/bob/Downloads/MyApp.app', file), file);8});9archive.toArchive().then(function(buffer) {10    console.log(buffer);11});12var zip = require('node-native-zip');13var archive = new zip();14var path = require('path');15var fs = require('fs');16var files = fs.readdirSync('/Users/bob/Downloads/MyApp.app');17files.forEach(function(file) {18    archive.add(path.join('/Users/bob/Downloads/MyApp.app', file), file);19});20var buffer = archive.writeBuffer();21console.log(buffer);22var zip = require('node-native-zip');23var archive = new zip();24var path = require('path');25var fs = require('fs');26var files = fs.readdirSync('/Users/bob/Downloads/MyApp.app');27files.forEach(function(file) {28    archive.add(path.join('/Users/bob/Downloads/MyApp.app', file), file);29});30archive.writeFile('myArchive.zip', function(err) {31    if (err) {32        console.log(err);33    } else {34        console.log('success');35    }36});37var zip = require('node-native-zip');38var archive = new zip();39var path = require('path');40var fs = require('fs');41var files = fs.readdirSync('/Users/bob/Downloads/MyApp.app');42files.forEach(function(file) {43    archive.add(path.join('/Users/bob/Downloads/MyApp.app', file), file);44});45archive.writeZip('myArchive.zip', function(err) {46    if (err) {47        console.log(err);48    } else {49        console.log('success');50    }51});52var zip = require('node-native-zip');53var archive = new zip();54var path = require('path');55var fs = require('fs');56var files = fs.readdirSync('/UsersLearn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
