How to use the got.head function in got

To help you get started, we’ve selected a few got 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 doyensec / electronegativity / src / finder / checks / GlobalChecks / AvailableSecurityFixesGlobalCheck.js View on Github external
async updateReleasesList() {

    var shouldUpdate = false;
    var ElectronReleaseData;
    var remoteEtag;
    var localEtag;


    if (!shouldUpdate) {
      var releaseFile = fs.readdirSync(this.releasesFilePath).filter(fn => fn.startsWith('releases.'));
      if (releaseFile.length > 0) { // file exists, we should check the etag
        try {
          ElectronReleaseData = await got.head('https://raw.githubusercontent.com/electron/releases/master/index.json');
        } catch (e) {
          console.log(chalk.yellow(`Something went wrong while fetching Electron's releases. No connectivity?`));
          return false;
        }
        var rawRemoteEtag = ElectronReleaseData.headers.etag;
        remoteEtag = rawRemoteEtag.match(this.githubEtagRegex);
        if (remoteEtag == null) {
          console.log(chalk.yellow(`Something went wrong while fetching Electron's releases. Etag returned from Github was not recognized.`));
          return false;
        } else remoteEtag = remoteEtag[0];
        localEtag = releaseFile[0].split('.')[1];

        //check if it corresponds to our local version
        if (localEtag === remoteEtag)
          shouldUpdate = false;
        else {
github Hughp135 / osustuff-tournaments / back-end / src / tasks / sync-beatmaps.ts View on Github external
logger.info(`Download unavailable for ${beatmap.beatmapset_id}.`);
        continue;
      }
      const existing = await Beatmap.findOne({
        beatmap_id: beatmap.beatmap_id,
      });
      if (existing) {
        existingMaps.push(beatmap.beatmap_id);
        continue;
      }

      await new Promise(res => setTimeout(res, 1500));

      try {
        // Check if beatmap is available for download. Will throw 404 if not
        await got.head(
          `https://osu.ppy.sh/beatmapsets/${beatmap.beatmapset_id}/download`,
          {},
        );
        // Add beatmap to database
        const newB = await Beatmap.create(beatmap);
        added.push(beatmap.beatmap_id);
        downloadAvailable.push(beatmap.beatmapset_id);
      } catch (e) {
        if (e.statusCode === 404) {
          // Unavailable to download
          logger.info(
            `Download not available for beatmap ${beatmap.beatmapset_id}.`,
          );
          downloadUnavailable.push(beatmap.beatmapset_id);
        } else if (e.statusCode === 429) {
          logger.info('Timed out, waiting one minute...');
github Human-Connection / Embed-API / src / services / embeds / embeds.class.js View on Github external
promises.push(new Promise(async (resolve, reject) => {
      try {
        let metadata = {};
        const head = await got.head(targetURL);
        if (head.headers['content-type'].indexOf('text') < 0) {
          if (head.headers['content-type']) {
            metadata.overwrite = {
              type: head.headers['content-type'].split('/').shift(),
              contentType: head.headers['content-type']
            };
          }
        } else {
          const { body: html, url } = await got(targetURL);
          metadata = await metascraper({ html, url });
        }

        data.metascraper = metadata;
        resolve(data);
      } catch (err) {
        resolve({err});
github electrode-io / electrode-native / ern-core / src / ErnBinaryStore.ts View on Github external
public async hasBinary(
    descriptor: AppVersionDescriptor,
    {
      flavor,
    }: {
      flavor?: string
    } = {}
  ): Promise {
    try {
      const res = await got.head(this.urlToBinary(descriptor, { flavor }), {
        ...this.gotCommonOpts,
      })
      return res.statusCode === 200
    } catch (err) {
      if (err.response && err.response.statusCode === 404) {
        return false
      }
      throw new Error(err.response?.text ?? err.message)
    }
  }
github nasa / cumulus / packages / ingest / http.js View on Github external
async sync(remotePath, bucket, key) {
    validateHost(this.provider.host);

    const remoteUrl = buildURL({
      protocol: this.provider.protocol,
      host: this.provider.host,
      port: this.provider.port,
      path: remotePath
    });

    const s3uri = buildS3Uri(bucket, key);
    log.info(`Sync ${remoteUrl} to ${s3uri}`);

    let headers = {};
    try {
      const headResponse = await got.head(remoteUrl);
      headers = headResponse.headers;
    } catch (err) {
      log.info(`HEAD failed for ${remoteUrl} with error: ${err}.`);
    }
    const contentType = headers['content-type'] || lookupMimeType(key);

    const pass = new PassThrough();
    got.stream(remoteUrl).pipe(pass);

    await promiseS3Upload({
      Bucket: bucket,
      Key: key,
      Body: pass,
      ContentType: contentType
    });
github heroku / cli / packages / ci-v5 / lib / source.js View on Github external
function * urlExists (url) {
  return yield got.head(url)
}
github gerhardberger / electron-pdf-window / index.js View on Github external
return new Promise((resolve, reject) => {
    if (isAlreadyLoadedWithPdfJs(url)) {
      resolve(false)
    } else if (isFile(url)) {
      resolve(getMimeOfFile(url) === 'application/pdf')
    } else if (hasPdfExtension(url)) {
      resolve(true)
    } else {
      got.head(url).then(res => {
        if (res.headers.location) {
          isPDF(res.headers.location).then(isit => resolve(isit))
          .catch(err => reject(err))
        } else {
          resolve(res.headers['content-type'].indexOf('application/pdf') !== -1)
        }
      }).catch(err => reject(err))
    }
  })
}
github nano-wallet-company / nano-wallet-desktop / ember-electron / assets.js View on Github external
const verifyAsset = async (url, savePath, onProgress) => {
  log.info('Downloading asset signature:', url);

  const { headers } = await got.head(url, {
    retries: 10,
    encoding: null,
    headers: {
      'user-agent': USER_AGENT,
    },
  });

  if (!headers[Symbol.keyFor(SIGNATURE_HEADER)]) {
    throw new Error('Signature header not found');
  }

  log.info('Verifying asset:', savePath);

  const start = Date.now();
  const verifier = crypto.createVerify('SHA256');
  const { size } = await fs.statAsync(savePath);
github sindresorhus / npm-name / index.js View on Github external
const isScopedPackage = isScoped(name);
	if (isScopedPackage) {
		name = name.replace(/\//g, '%2f');
	}

	const authInfo = registryAuthToken(registryUrl, {recursive: true});
	const headers = {};
	if (authInfo) {
		headers.authorization = `${authInfo.type} ${authInfo.token}`;
	}

	try {
		if (isOrganization) {
			await got.head(npmOrganizationUrl + name.toLowerCase(), {timeout: 10000});
		} else {
			await got.head(registryUrl + name.toLowerCase(), {timeout: 10000, headers});
		}

		return false;
	} catch (error) {
		if (error.statusCode === 404) {
			return true;
		}

		if (isScopedPackage && error.statusCode === 401) {
			return true;
		}

		throw error;
	}
};