fs-extra#unlink TypeScript Examples

The following examples show how to use fs-extra#unlink. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.ts    From cli with MIT License 7 votes vote down vote up
removeUselessFiles = async (target: string) => {
  const nm = join(target, 'node_modules');
  const list = await globby(uselessFilesMatch, {
    cwd: nm,
    deep: 10,
  });
  console.log('  - Useless files Count', list.length);
  let size = 0;
  for (const file of list) {
    const path = join(nm, file);
    if (existsSync(path)) {
      const stats = await stat(path);
      size += stats.size;
      await unlink(path);
    }
  }
  console.log(
    `  - Remove Useless file ${Number(size / (2 << 19)).toFixed(2)} MB`
  );
}
Example #2
Source File: videoToGif.ts    From wa-sticker-formatter with MIT License 6 votes vote down vote up
videoToGif = async (data: Buffer): Promise<Buffer> => {
    const filename = `${tmpdir()}/${Math.random().toString(36)}`
    const [video, gif] = ['video', 'gif'].map((ext) => `${filename}.${ext}`)
    await writeFile(video, data)
    await new Promise((resolve) => {
        ffmpeg(video).save(gif).on('end', resolve)
    })
    const buffer = await readFile(gif)
    ;[video, gif].forEach((file) => unlink(file))
    return buffer
}
Example #3
Source File: DownloadedUpdateHelper.ts    From electron-differential-updater with MIT License 6 votes vote down vote up
export async function createTempUpdateFile(name: string, cacheDir: string, log: Logger): Promise<string> {
  // https://github.com/electron-userland/electron-builder/pull/2474#issuecomment-366481912
  let nameCounter = 0
  let result = path.join(cacheDir, name)
  for (let i = 0; i < 3; i++) {
    try {
      await unlink(result)
      return result
    }
    catch (e) {
      if (e.code === "ENOENT") {
        return result
      }

      log.warn(`Error on remove temp update file: ${e}`)
      result = path.join(cacheDir, `${nameCounter++}-${name}`)
    }
  }
  return result
}
Example #4
Source File: AppUpdater.ts    From electron-differential-updater with MIT License 4 votes vote down vote up
protected async executeDownload(
    taskOptions: DownloadExecutorTask
  ): Promise<Array<string>> {
    const fileInfo = taskOptions.fileInfo;
    const downloadOptions: DownloadOptions = {
      headers: taskOptions.downloadUpdateOptions.requestHeaders,
      cancellationToken: taskOptions.downloadUpdateOptions.cancellationToken,
      sha2: (fileInfo.info as any).sha2,
      sha512: fileInfo.info.sha512
    };

    if (this.listenerCount(DOWNLOAD_PROGRESS) > 0) {
      downloadOptions.onProgress = it => this.emit(DOWNLOAD_PROGRESS, it);
    }

    const updateInfo =
      taskOptions.downloadUpdateOptions.updateInfoAndProvider.info;
    const version = updateInfo.version;
    const packageInfo = fileInfo.packageInfo;
    const {
      configuration
    } = taskOptions.downloadUpdateOptions.updateInfoAndProvider.provider;
    function getCacheUpdateFileName(): string {
      // NodeJS URL doesn't decode automatically
      const urlPath = decodeURIComponent(taskOptions.fileInfo.url.pathname);
      if (urlPath.endsWith(`.${taskOptions.fileExtension}`)) {
        return path.posix.basename(urlPath);
      } else {
        // url like /latest, generate name
        return `update.${taskOptions.fileExtension}`;
      }
    }
    const useAppSupportCache = configuration ? configuration.useAppSupportCache : false;
    const downloadedUpdateHelper = await this.getOrCreateDownloadHelper(
      useAppSupportCache
    );
    const cacheDir = downloadedUpdateHelper.cacheDirForPendingUpdate;
    await ensureDir(cacheDir);
    const updateFileName = getCacheUpdateFileName();
    let updateFile = path.join(cacheDir, updateFileName);
    const packageFile =
      packageInfo == null
        ? null
        : path.join(
            cacheDir,
            `package-${version}${path.extname(packageInfo.path) || ".7z"}`
          );

    const done = async (isSaveCache: boolean) => {
      await downloadedUpdateHelper.setDownloadedFile(
        updateFile,
        packageFile,
        updateInfo,
        fileInfo,
        updateFileName,
        isSaveCache
      );
      await taskOptions.done!!({
        ...updateInfo,
        downloadedFile: updateFile
      });
      return packageFile == null ? [updateFile] : [updateFile, packageFile];
    };

    const log = this._logger;
    const cachedUpdateFile = await downloadedUpdateHelper.validateDownloadedPath(
      updateFile,
      updateInfo,
      fileInfo,
      log
    );
    if (cachedUpdateFile != null) {
      updateFile = cachedUpdateFile;
      return await done(false);
    }

    const removeFileIfAny = async () => {
      await downloadedUpdateHelper.clear().catch(() => {
        // ignore
      });
      return await unlink(updateFile).catch(() => {
        // ignore
      });
    };

    const tempUpdateFile = await createTempUpdateFile(
      `temp-${updateFileName}`,
      cacheDir,
      log
    );
    try {
      await taskOptions.task(
        tempUpdateFile,
        downloadOptions,
        packageFile,
        removeFileIfAny
      );
      await rename(tempUpdateFile, updateFile);
    } catch (e) {
      await removeFileIfAny();

      if (e instanceof CancellationError) {
        log.info("cancelled");
        this.emit("update-cancelled", updateInfo);
      }
      throw e;
    }

    log.info(`New version ${version} has been downloaded to ${updateFile}`);
    return await done(true);
  }
Example #5
Source File: NsisUpdater.ts    From electron-differential-updater with MIT License 4 votes vote down vote up
/*** @private */
  protected doDownloadUpdate(
    downloadUpdateOptions: DownloadUpdateOptions
  ): Promise<Array<string>> {
    const provider = downloadUpdateOptions.updateInfoAndProvider.provider;
    const fileInfo = findFile(
      provider.resolveFiles(downloadUpdateOptions.updateInfoAndProvider.info),
      "exe"
    )!!;
    return this.executeDownload({
      fileExtension: "exe",
      downloadUpdateOptions,
      fileInfo,
      task: async (
        destinationFile,
        downloadOptions,
        packageFile,
        removeTempDirIfAny
      ) => {
        if (
          hasQuotes(destinationFile) ||
          (packageFile != null && hasQuotes(packageFile))
        ) {
          throw newError(
            `destinationFile or packageFile contains illegal chars`,
            "ERR_UPDATER_ILLEGAL_FILE_NAME"
          );
        }

        const packageInfo = fileInfo.packageInfo;
        const isWebInstaller = packageInfo != null && packageFile != null;
        if (
          isWebInstaller ||
          (await this.differentialDownloadInstaller(
            fileInfo,
            downloadUpdateOptions,
            destinationFile,
            provider
          ))
        ) {
          await this.httpExecutor.download(
            fileInfo.url,
            destinationFile,
            downloadOptions
          );
        }

        const signatureVerificationStatus = await this.verifySignature(
          destinationFile
        );
        if (signatureVerificationStatus != null) {
          await removeTempDirIfAny();
          // noinspection ThrowInsideFinallyBlockJS
          throw newError(
            `New version ${downloadUpdateOptions.updateInfoAndProvider.info.version} is not signed by the application owner: ${signatureVerificationStatus}`,
            "ERR_UPDATER_INVALID_SIGNATURE"
          );
        }

        if (isWebInstaller) {
          if (
            await this.differentialDownloadWebPackage(
              packageInfo!!,
              packageFile!!,
              provider
            )
          ) {
            try {
              await this.httpExecutor.download(
                new URL(packageInfo!!.path),
                packageFile!!,
                {
                  headers: downloadUpdateOptions.requestHeaders,
                  cancellationToken: downloadUpdateOptions.cancellationToken,
                  sha512: packageInfo!!.sha512
                }
              );
            } catch (e) {
              try {
                await unlink(packageFile!!);
              } catch (ignored) {
                // ignore
              }

              throw e;
            }
          }
        }
      }
    });
  }