feat: load chromium binary remote

This commit is contained in:
Vu Nguyen 2023-01-05 16:40:05 +00:00
parent b286dc3fc2
commit 3deea91193
2 changed files with 34 additions and 2 deletions

29
source/helper.ts Normal file
View File

@ -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<string> => 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)
});
});
})

View File

@ -3,6 +3,7 @@ import { IncomingMessage } from 'node:http';
import LambdaFS from './lambdafs'; import LambdaFS from './lambdafs';
import { join } from 'node:path'; import { join } from 'node:path';
import { URL } from 'node:url'; 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 */ /** Viewport taken from https://github.com/puppeteer/puppeteer/blob/main/docs/api/puppeteer.viewport.md */
interface Viewport { interface Viewport {
@ -183,14 +184,16 @@ class Chromium {
* @returns The path to the `chromium` binary * @returns The path to the `chromium` binary
*/ */
static async executablePath(input?: string): Promise<string> { static async executablePath(input?: string): Promise<string> {
/** /**
* If the `chromium` binary already exists in /tmp/chromium, return it. * 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'); 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, * If input is defined, use that as the location of the brotli files,
* otherwise, the default location is ../bin. * otherwise, the default location is ../bin.