當前位置: 首頁>>代碼示例>>TypeScript>>正文


TypeScript fs-extra-p.open函數代碼示例

本文整理匯總了TypeScript中fs-extra-p.open函數的典型用法代碼示例。如果您正苦於以下問題:TypeScript open函數的具體用法?TypeScript open怎麽用?TypeScript open使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了open函數的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。

示例1: build

  async build(appOutDir: string, arch: Arch): Promise<any> {
    const packager = this.packager

    // avoid spaces in the file name
    const image = path.join(this.outDir, packager.generateName("AppImage", arch, true))
    const appInfo = packager.appInfo
    await unlinkIfExists(image)

    const appImagePath = await appImagePathPromise
    const args = [
      "-joliet", "on",
      "-volid", "AppImage",
      "-dev", image,
      "-padding", "0",
      "-map", appOutDir, "/usr/bin",
      "-map", path.join(__dirname, "..", "..", "templates", "linux", "AppRun.sh"), `/AppRun`,
      "-map", await this.desktopEntry, `/${appInfo.name}.desktop`,
      "-move", `/usr/bin/${appInfo.productFilename}`, `/usr/bin/${appInfo.name}`,
    ]
    for (let [from, to] of (await this.helper.icons)) {
      args.push("-map", from, `/usr/share/icons/default/${to}`)
    }

    // must be after this.helper.icons call
    if (this.helper.maxIconPath == null) {
      throw new Error("Icon is not provided")
    }
    args.push("-map", this.helper.maxIconPath, "/.DirIcon")

    args.push("-chown_r", "0", "/", "--")
    args.push("-zisofs", `level=${packager.devMetadata.build.compression === "store" ? "0" : "9"}:block_size=128k:by_magic=off`)
    args.push("set_filter_r", "--zisofs", "/")

    await exec(process.env.USE_SYSTEM_FPM === "true" || process.arch !== "x64" ? "xorriso" : path.join(appImagePath, "xorriso"), args)

    await new BluebirdPromise((resolve, reject) => {
      const rd = createReadStream(path.join(appImagePath, arch === Arch.ia32 ? "32" : "64", "runtime"))
      rd.on("error", reject)
      const wr = createWriteStream(image, {flags: "r+"})
      wr.on("error", reject)
      wr.on("finish", resolve)
      rd.pipe(wr)
    })

    const fd = await open(image, "r+")
    try {
      const magicData = new Buffer([0x41, 0x49, 0x01])
      await write(fd, magicData, 0, magicData.length, 8)
    }
    finally {
      await close(fd)
    }

    await chmod(image, "0755")

    packager.dispatchArtifactCreated(image, packager.generateName("AppImage", arch, true))
  }
開發者ID:SimplyAhmazing,項目名稱:electron-builder,代碼行數:57,代碼來源:appImage.ts

示例2: readEmbeddedBlockMapData

async function readEmbeddedBlockMapData(file: string): Promise<BlockMap> {
  const fd = await open(file, "r")
  try {
    const fileSize = (await fstat(fd)).size
    const sizeBuffer = Buffer.allocUnsafe(4)
    await read(fd, sizeBuffer, 0, sizeBuffer.length, fileSize - sizeBuffer.length)

    const dataBuffer = Buffer.allocUnsafe(sizeBuffer.readUInt32BE(0))
    await read(fd, dataBuffer, 0, dataBuffer.length, fileSize - sizeBuffer.length - dataBuffer.length)
    await close(fd)

    return readBlockMap(dataBuffer)
  }
  catch (e) {
    await close(fd)
    throw e
  }
}
開發者ID:electron-userland,項目名稱:electron-builder,代碼行數:18,代碼來源:FileWithEmbeddedBlockMapDifferentialDownloader.ts

示例3: checkIcon

async function checkIcon(file: string): Promise<void> {
  const fd = await open(file, "r")
  const buffer = new Buffer(512)
  try {
    await read(fd, buffer, 0, buffer.length, 0)
  }
  finally {
    await close(fd)
  }

  const sizes = parseIco(buffer)
  for (let size of sizes) {
    if (size.w >= 256 && size.h >= 256) {
      return
    }
  }

  throw new Error("Windows icon image size must be at least 256x256")
}
開發者ID:alatzidis,項目名稱:electron-builder,代碼行數:19,代碼來源:winPackager.ts

示例4: readEmbeddedBlockMapData

export async function readEmbeddedBlockMapData(file: string) {
  const fd = await open(file, "r")
  try {
    const fileSize = (await fstat(fd)).size
    const sizeBuffer = Buffer.allocUnsafe(4)
    await read(fd, sizeBuffer, 0, sizeBuffer.length, fileSize - sizeBuffer.length)

    const dataBuffer = Buffer.allocUnsafe(sizeBuffer.readUInt32BE(0))
    await read(fd, dataBuffer, 0, dataBuffer.length, fileSize - sizeBuffer.length - dataBuffer.length)
    await close(fd)

    const inflateRaw: any = BluebirdPromise.promisify(require("zlib").inflateRaw)
    return (await inflateRaw(dataBuffer)).toString()
  }
  catch (e) {
    await close(fd)
    throw e
  }
}
開發者ID:ledinhphuong,項目名稱:electron-builder,代碼行數:19,代碼來源:blockMapApi.ts

示例5: computeBlocks

async function computeBlocks(inputFile: string, stat: Stats): Promise<Array<string>> {
  const fd = await open(inputFile, "r")

  const chunkSize = 64 * 1024
  const buffer = Buffer.allocUnsafe(chunkSize)
  const size = stat.size
  const blocks = []

  for (let offset = 0; offset < size; offset += chunkSize) {
    const actualChunkSize = Math.min(size - offset, chunkSize)
    await read(fd, buffer, 0, actualChunkSize, offset)

    const hash = createHash("sha256")
    hash.update(actualChunkSize === chunkSize ? buffer : buffer.slice(0, actualChunkSize))
    blocks.push(hash.digest("base64"))
  }

  return blocks
}
開發者ID:yuya-oc,項目名稱:electron-builder,代碼行數:19,代碼來源:blockMap.ts

示例6: safeLoad

      packed: async context => {
        const outDir = context.outDir
        outDirs.push(outDir)
        const targetOutDir = path.join(outDir, "nsis-web")
        const updateInfoFile = path.join(targetOutDir, "latest.yml")

        const updateInfo: UpdateInfo = safeLoad(await readFile(updateInfoFile, "utf-8"))
        const fd = await open(path.join(targetOutDir, `TestApp-${version}-x64.nsis.7z`), "r")
        try {
          const packageInfo = updateInfo.packages!!.x64
          const buffer = Buffer.allocUnsafe(packageInfo.blockMapSize!!)
          await read(fd, buffer, 0, buffer.length, packageInfo.size - buffer.length)
          const inflateRaw: any = BluebirdPromise.promisify(require("zlib").inflateRaw)
          const blockMapData = (await inflateRaw(buffer)).toString()
          await writeFile(path.join(outDir, "win-unpacked", BLOCK_MAP_FILE_NAME), blockMapData)
        }
        finally {
          await close(fd)
        }
      }
開發者ID:jwheare,項目名稱:electron-builder,代碼行數:20,代碼來源:differentialUpdateTest.ts

示例7: checkIcon

async function checkIcon(file: string): Promise<void> {
  const fd = await open(file, "r")
  const buffer = new Buffer(512)
  try {
    await read(fd, buffer, 0, buffer.length, 0)
  }
  finally {
    await close(fd)
  }

  if (!isIco(buffer)) {
    throw new Error(`Windows icon is not valid ico file, please fix "${file}"`)
  }

  const sizes = parseIco(buffer)
  for (let size of sizes) {
    if (size!.w >= 256 && size!.h >= 256) {
      return
    }
  }

  throw new Error(`Windows icon size must be at least 256x256, please fix "${file}"`)
}
開發者ID:mairanteodoro,項目名稱:electron-builder,代碼行數:23,代碼來源:winPackager.ts

示例8: downloadFile

  private async downloadFile(tasks: Array<Operation>): Promise<any> {
    const signature = this.signatureSize === 0 ? null : await this.readRemoteBytes(0, this.signatureSize - 1)

    const oldFileFd = await open(this.options.oldFile, "r")
    const newFileFd = await open(this.options.newFile, "w")
    const fileOut = createWriteStream(this.options.newFile, {fd: newFileFd})
    await new BluebirdPromise((resolve, reject) => {
      const streams: Array<any> = []
      const digestTransform = new DigestTransform(this.blockAwareFileInfo.sha512)
      // to simply debug, do manual validation to allow file to be fully written
      digestTransform.isValidateOnEnd = false
      streams.push(digestTransform)

      // noinspection JSArrowFunctionCanBeReplacedWithShorthand
      fileOut.on("finish", () => {
        (fileOut.close as any)(() => {
          try {
            digestTransform.validate()
          }
          catch (e) {
            reject(e)
            return
          }

          resolve()
        })
      })

      streams.push(fileOut)

      let lastStream = null
      for (const stream of streams) {
        stream.on("error", reject)
        if (lastStream == null) {
          lastStream = stream
        }
        else {
          lastStream = lastStream.pipe(stream)
        }
      }

      const firstStream = streams[0]

      let w: any
      if (this.options.useMultipleRangeRequest) {
        w = executeTasks(this, tasks, firstStream, oldFileFd, reject)
      }
      else {
        let attemptCount = 0
        let actualUrl: string | null = null
        this.logger.info(`Differential download: ${this.options.newUrl}`)
        w = (index: number) => {
          if (index >= tasks.length) {
            if (this.fileMetadataBuffer != null) {
              firstStream.write(this.fileMetadataBuffer)
            }
            firstStream.end()
            return
          }

          const operation = tasks[index++]
          if (operation.kind === OperationKind.COPY) {
            copyData(operation, firstStream, oldFileFd, reject, () => w(index))
          }
          else {
            const requestOptions = this.createRequestOptions("get", actualUrl)
            const range = `bytes=${operation.start}-${operation.end - 1}`
            requestOptions.headers!!.Range = range;
            (requestOptions as any).redirect = "manual"

            const debug = this.logger.debug
            if (debug != null) {
              debug(`effective url: ${actualUrl == null ? "" : removeQuery(actualUrl)}, range: ${range}`)
            }

            const request = this.httpExecutor.doRequest(requestOptions, response => {
              // Electron net handles redirects automatically, our NodeJS test server doesn't use redirects - so, we don't check 3xx codes.
              if (response.statusCode >= 400) {
                reject(createHttpError(response))
              }

              response.pipe(firstStream, {
                end: false
              })
              response.once("end", () => {
                if (++attemptCount === 100) {
                  attemptCount = 0
                  setTimeout(() => w(index), 1000)
                }
                else {
                  w(index)
                }
              })
            })
            request.on("redirect", (statusCode: number, method: string, redirectUrl: string) => {
              this.logger.info(`Redirect to ${removeQuery(redirectUrl)}`)
              actualUrl = redirectUrl
              request.followRedirect()
            })
            this.httpExecutor.addErrorAndTimeoutHandlers(request, reject)
//.........這裏部分代碼省略.........
開發者ID:ledinhphuong,項目名稱:electron-builder,代碼行數:101,代碼來源:DifferentialDownloader.ts

示例9: build

  async build(appOutDir: string, arch: Arch): Promise<any> {
    const packager = this.packager

    const image = path.join(this.outDir, packager.generateName(null, arch, true))
    const appInfo = packager.appInfo
    await unlinkIfExists(image)

    const appImagePath = await appImagePathPromise
    const args = [
      "-joliet", "on",
      "-volid", "AppImage",
      "-dev", image,
      "-padding", "0",
      "-map", appOutDir, "/usr/bin",
      "-map", path.join(__dirname, "..", "..", "templates", "linux", "AppRun.sh"), `/AppRun`,
      "-map", await this.desktopEntry, `/${appInfo.name}.desktop`,
      "-move", `/usr/bin/${appInfo.productFilename}`, "/usr/bin/app",
    ]
    for (let [from, to] of (await this.helper.icons)) {
      args.push("-map", from, `/usr/share/icons/default/${to}`)
    }

    // must be after this.helper.icons call
    if (this.helper.maxIconPath == null) {
      throw new Error("Icon is not provided")
    }
    args.push("-map", this.helper.maxIconPath, "/.DirIcon")

    // args.push("-zisofs", `level=0:block_size=128k:by_magic=off`, "-chown_r", "0")
    // args.push("/", "--", "set_filter_r", "--zisofs", "/")

    await exec(process.platform === "darwin" ? path.join(appImagePath, "xorriso") : "xorriso", args)

    await new BluebirdPromise((resolve, reject) => {
      const rd = createReadStream(path.join(appImagePath, arch === Arch.ia32 ? "32" : "64", "runtime"))
      rd.on("error", reject)
      const wr = createWriteStream(image)
      wr.on("error", reject)
      wr.on("finish", resolve)
      rd.pipe(wr)
    })

    const fd = await open(image, "r+")
    try {
      const magicData = new Buffer([0x41, 0x49, 0x01])
      await write(fd, magicData, 0, magicData.length, 8)
    }
    finally {
      await close(fd)
    }

    await chmod(image, "0755")
    // we archive because you cannot distribute exe as is - e.g. Ubuntu clear exec flag and user cannot just click on AppImage to run
    // also, LZMA compression - 29MB vs zip 42MB
    // we use slow xz instead of 7za because 7za doesn't preserve exec file permissions for xz
    await spawn("xz", ["--x86", "--lzma2", "--compress", "--force", packager.devMetadata.build.compression === "store" ? "-0" : "-9e", image], {
      cwd: path.dirname(image),
      stdio: ["ignore", debug.enabled ? "inherit" : "ignore", "inherit"],
    })

    packager.dispatchArtifactCreated(image)
  }
開發者ID:reactsnipp,項目名稱:electron-builder,代碼行數:62,代碼來源:appImage.ts

示例10: downloadFile

  private async downloadFile(operations: Array<Operation>) {
    // todo we can avoid download remote and construct manually
    const signature = await this.readRemoteBytes(0, SIGNATURE_HEADER_SIZE - 1)

    const oldFileFd = await open(this.options.oldPackageFile, "r")
    await new BluebirdPromise((resolve, reject) => {
      const streams: Array<any> = []
      const digestTransform = new DigestTransform(this.packageInfo.sha512)
      // to simply debug, do manual validation to allow file to be fully written
      digestTransform.isValidateOnEnd = false
      streams.push(digestTransform)

      const fileOut = createWriteStream(this.options.packagePath)
      fileOut.on("finish", () => {
        (fileOut.close as any)(() => {
          try {
            digestTransform.validate()
          }
          catch (e) {
            reject(e)
            return
          }

          resolve()
        })
      })

      streams.push(fileOut)

      let lastStream = null
      for (const stream of streams) {
        stream.on("error", reject)
        if (lastStream == null) {
          lastStream = stream
        }
        else {
          lastStream = lastStream.pipe(stream)
        }
      }

      const firstStream = streams[0]

      const w = (index: number) => {
        if (index >= operations.length) {
          firstStream.end(this.fileMetadataBuffer)
          return
        }

        const operation = operations[index++]

        if (operation.kind === OperationKind.COPY) {
          const readStream = createReadStream(this.options.oldPackageFile, {
            fd: oldFileFd,
            autoClose: false,
            start: operation.start,
            // end is inclusive
            end: operation.end - 1,
          })
          readStream.on("error", reject)
          readStream.once("end", () => w(index))
          readStream.pipe(firstStream, {
            end: false
          })
        }
        else {
          // https://github.com/electron-userland/electron-builder/issues/1523#issuecomment-327084661
          // todo to reduce http requests we need to consolidate non sequential download operations (Multipart ranges)
          const requestOptions = this.createRequestOptions("get")
          requestOptions.headers!!.Range = `bytes=${operation.start}-${operation.end - 1}`
          const request = this.httpExecutor.doRequest(requestOptions, response => {
            // Electron net handles redirects automatically, our NodeJS test server doesn't use redirects - so, we don't check 3xx codes.
            if (response.statusCode >= 400) {
              reject(new HttpError(response))
            }

            response.pipe(firstStream, {
              end: false
            })
            response.once("end", () => w(index))
          })
          this.httpExecutor.addErrorAndTimeoutHandlers(request, reject)
          request.end()
        }
      }

      firstStream.write(signature, () => w(0))
    })
      .finally(() => close(oldFileFd))
  }
開發者ID:jwheare,項目名稱:electron-builder,代碼行數:89,代碼來源:differentialPackage.ts


注:本文中的fs-extra-p.open函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。