diff --git a/CHANGELOG.md b/CHANGELOG.md index 3c6d0909..89b310c7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,10 @@ - Add `--watch` (`-w`) option to support watch mode ([#18](https://github.com/marp-team/marp-cli/pull/18)) +### Fixed + +- Use singleton Chrome instance to convert into PDF ([#19](https://github.com/marp-team/marp-cli/pull/19)) + ## v0.0.8 - 2018-09-15 ### Added diff --git a/src/converter.ts b/src/converter.ts index ec1933d9..229c4232 100644 --- a/src/converter.ts +++ b/src/converter.ts @@ -112,9 +112,9 @@ export class Converter { try { const browser = await Converter.runBrowser() + const page = await browser.newPage() try { - const page = await browser.newPage() await page.goto(uri, { waitUntil: ['domcontentloaded', 'networkidle0'], }) @@ -124,13 +124,19 @@ export class Converter { preferCSSPageSize: true, }) } finally { - await browser.close() + await page.close() } } finally { if (tmpFile) await tmpFile.cleanup() } } + static async closeBrowser() { + if (Converter.browser) await Converter.browser.close() + } + + private static browser?: puppeteer.Browser + private generateEngine(mergeOptions: MarpitOptions) { const { html, options } = this.options const opts: any = { ...options, ...mergeOptions } @@ -149,18 +155,25 @@ export class Converter { return engine } - private static runBrowser() { - const args: string[] = [] - const finder: () => string[] = require('is-wsl') - ? chromeFinder.wsl - : chromeFinder[process.platform] + private static async runBrowser() { + if (!Converter.browser) { + const args: string[] = [] + const finder: () => string[] = require('is-wsl') + ? chromeFinder.wsl + : chromeFinder[process.platform] - if (process.env.IS_DOCKER) - args.push('--no-sandbox', '--disable-dev-shm-usage') + if (process.env.IS_DOCKER) + args.push('--no-sandbox', '--disable-dev-shm-usage') - return puppeteer.launch({ - args, - executablePath: finder ? finder()[0] : undefined, - }) + Converter.browser = await puppeteer.launch({ + args, + executablePath: finder ? finder()[0] : undefined, + }) + + Converter.browser.once('disconnected', () => { + Converter.browser = undefined + }) + } + return Converter.browser } } diff --git a/src/marp-cli.ts b/src/marp-cli.ts index ce1fe6fc..02f122d2 100644 --- a/src/marp-cli.ts +++ b/src/marp-cli.ts @@ -176,5 +176,7 @@ export default async function(argv: string[] = []): Promise { cli.error(e.message) return e.errorCode + } finally { + await Converter.closeBrowser() } } diff --git a/test/converter.ts b/test/converter.ts index 30c03838..74ea6ece 100644 --- a/test/converter.ts +++ b/test/converter.ts @@ -10,6 +10,7 @@ import { CLIError } from '../src/error' jest.mock('fs') +afterAll(() => Converter.closeBrowser()) afterEach(() => jest.restoreAllMocks()) describe('Converter', () => {