From 3deea911935bef555fc129a36faac8a1bb3d58d6 Mon Sep 17 00:00:00 2001 From: Vu Nguyen <54926438+aqaurius6666@users.noreply.github.com> Date: Thu, 5 Jan 2023 16:40:05 +0000 Subject: [PATCH] feat: load chromium binary remote --- source/helper.ts | 29 +++++++++++++++++++++++++++++ source/index.ts | 7 +++++-- 2 files changed, 34 insertions(+), 2 deletions(-) create mode 100644 source/helper.ts diff --git a/source/helper.ts b/source/helper.ts new file mode 100644 index 0000000..ae80500 --- /dev/null +++ b/source/helper.ts @@ -0,0 +1,29 @@ +import { unlink } from "node:fs"; +import { get } from "node:https"; +import { tmpdir } from "node:os"; +import { extract } from 'tar-fs'; + +export const isValidUrl = (input: string) => { + try { + return !!new URL(input); + } catch (err) { + return false; + } +} + +export const downloadAndExtract = async (url: string): Promise => new Promise((resolve, reject) => { + const destDir = `${tmpdir()}/chromium-pack` + const extractObj = extract(destDir) + get(url, function (response) { + response.pipe(extractObj); + extractObj.on('finish', () => { + extractObj.end(() => { + resolve(destDir); + }); + }); + }).on('error', (err) => { + unlink(destDir, (_) => { + reject(err) + }); + }); +}) diff --git a/source/index.ts b/source/index.ts index b7c7769..3ad8b87 100644 --- a/source/index.ts +++ b/source/index.ts @@ -3,6 +3,7 @@ import { IncomingMessage } from 'node:http'; import LambdaFS from './lambdafs'; import { join } from 'node:path'; import { URL } from 'node:url'; +import { downloadAndExtract, isValidUrl } from './helper'; /** Viewport taken from https://github.com/puppeteer/puppeteer/blob/main/docs/api/puppeteer.viewport.md */ interface Viewport { @@ -183,14 +184,16 @@ class Chromium { * @returns The path to the `chromium` binary */ static async executablePath(input?: string): Promise { - /** * If the `chromium` binary already exists in /tmp/chromium, return it. */ - if (existsSync('/tmp/chromium') === true && input === undefined) { + if (existsSync('/tmp/chromium') === true) { return Promise.resolve('/tmp/chromium'); } + if (input && isValidUrl(input)) { + return this.executablePath(await downloadAndExtract(input)); + } /** * If input is defined, use that as the location of the brotli files, * otherwise, the default location is ../bin.