Skip to content

Commit

Permalink
feat: use browser context #138
Browse files Browse the repository at this point in the history
This feature uses puppeteer.BrowserContext for the convertion tasks.
Now, not for each task, an own browser instance is instantiated, but
only one. This one and only is used, and only browserContexts are passed
down to the convertion functions.
Reduces CPU Load, eliminates EventEmitter warnings and speed up
conversion of large amount of files by ~50%.
  • Loading branch information
chamabreu committed Nov 3, 2022
1 parent e51c3b6 commit fccf275
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 14 deletions.
14 changes: 10 additions & 4 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import getPort from 'get-port';
import getStdin from 'get-stdin';
import Listr from 'listr';
import path from 'path';
import puppeteer from 'puppeteer';
import { PackageJson } from '.';
import { Config, defaultConfig } from './lib/config';
import { help } from './lib/help';
Expand Down Expand Up @@ -64,6 +65,7 @@ main(cliFlags, defaultConfig).catch((error) => {

async function main(args: typeof cliFlags, config: Config) {
setProcessAndTermTitle('md-to-pdf');
const browser = await puppeteer.launch({ devtools: config.devtools, ...config.launch_options });

if (!validateNodeVersion()) {
throw new Error('Please use a Node.js version that satisfies the version specified in the engines field.');
Expand Down Expand Up @@ -125,25 +127,28 @@ async function main(args: typeof cliFlags, config: Config) {
*/

if (stdin) {
await convertMdToPdf({ content: stdin }, config, args)
const stdContext = await browser.createIncognitoBrowserContext();
await convertMdToPdf({ content: stdin }, config, args, stdContext)
.then(async () => closeServer(server))
.catch(async (error: Error) => {
await closeServer(server);

throw error;
});

await browser.close();

return;
}

const listrContext = await browser.createIncognitoBrowserContext();
const getListrTask = (file: string) => ({
title: `generating ${args['--as-html'] ? 'HTML' : 'PDF'} from ${chalk.underline(file)}`,
task: async () => convertMdToPdf({ path: file }, config, args),
task: async () => convertMdToPdf({ path: file }, config, args, listrContext),
});

await new Listr(files.map(getListrTask), { concurrent: true, exitOnError: false })
.run()
.then(() => {
.then(async () => {
if (args['--watch']) {
console.log(chalk.bgBlue('\n watching for changes \n'));

Expand All @@ -155,6 +160,7 @@ async function main(args: typeof cliFlags, config: Config) {
new Listr([getListrTask(file)], { exitOnError: false }).run().catch(console.error),
);
} else {
await browser.close();
server.close();
}
})
Expand Down
5 changes: 4 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#!/usr/bin/env node

import getPort from 'get-port';
import puppeteer from 'puppeteer';
import { Config, defaultConfig, HtmlConfig, PdfConfig } from './lib/config';
import { HtmlOutput, Output, PdfOutput } from './lib/generate-output';
import { getDir } from './lib/helpers';
Expand Down Expand Up @@ -50,7 +51,9 @@ export async function mdToPdf(input: Input, config: Partial<Config> = {}): Promi

const server = await serveDirectory(mergedConfig);

const pdf = await convertMdToPdf(input, mergedConfig);
const browser = await puppeteer.launch({ devtools: config.devtools, ...config.launch_options });
const md2pdfContext = await browser.createIncognitoBrowserContext();
const pdf = await convertMdToPdf(input, mergedConfig, undefined, md2pdfContext);

server.close();

Expand Down
15 changes: 7 additions & 8 deletions src/lib/generate-output.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,16 @@ interface BasicOutput {
filename: string | undefined;
}

interface GenerateOutputProps {
html: string;
relativePath: string;
config: PdfConfig | HtmlConfig | Config;
browser: puppeteer.BrowserContext;
}
/**
* Generate the output (either PDF or HTML).
*/
export async function generateOutput(html: string, relativePath: string, config: PdfConfig): Promise<PdfOutput>;
export async function generateOutput(html: string, relativePath: string, config: HtmlConfig): Promise<HtmlOutput>;
export async function generateOutput(html: string, relativePath: string, config: Config): Promise<Output>;
export async function generateOutput(html: string, relativePath: string, config: Config): Promise<Output> {
const browser = await puppeteer.launch({ devtools: config.devtools, ...config.launch_options });

export async function generateOutput({ html, relativePath, config, browser }: GenerateOutputProps): Promise<Output> {
const page = await browser.newPage();

// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
Expand Down Expand Up @@ -65,7 +66,5 @@ export async function generateOutput(html: string, relativePath: string, config:
outputFileContent = await page.pdf(config.pdf_options);
}

await browser.close();

return config.devtools ? (undefined as any) : { filename: config.dest, content: outputFileContent };
}
4 changes: 3 additions & 1 deletion src/lib/md-to-pdf.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { promises as fs } from 'fs';
import grayMatter from 'gray-matter';
import { dirname, resolve } from 'path';
import puppeteer from 'puppeteer';
import { Config } from './config';
import { generateOutput } from './generate-output';
import { getHtml } from './get-html';
Expand All @@ -17,6 +18,7 @@ export const convertMdToPdf = async (
input: { path: string } | { content: string },
config: Config,
args: CliArgs = {} as CliArgs,
browser: puppeteer.BrowserContext,
) => {
const mdFileContent =
'content' in input
Expand Down Expand Up @@ -87,7 +89,7 @@ export const convertMdToPdf = async (

const relativePath = 'path' in input ? resolve(input.path).replace(config.basedir, '') : '/';

const output = await generateOutput(html, relativePath, config);
const output = await generateOutput({ html, relativePath, config, browser });

if (!output) {
if (config.devtools) {
Expand Down

0 comments on commit fccf275

Please sign in to comment.