Skip to content

Commit

Permalink
chore(agnostification): common/helper.ts
Browse files Browse the repository at this point in the history
The `readProtocolStream` method uses `fs` only if you want to write to a
file. So we gate at the start of the function and ensure that if we got
given a path we are not in a Node environment.

We then use `import('fs')` to lazily load fs. We have multiple calls but
they will be cached so I don't believe that it's going to be a perf hit.
  • Loading branch information
jackfranklin committed Oct 15, 2020
1 parent 637a1f7 commit ded9c0f
Showing 1 changed file with 11 additions and 3 deletions.
14 changes: 11 additions & 3 deletions src/common/helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,11 @@
*/
import { TimeoutError } from './Errors.js';
import { debug } from './Debug.js';
import * as fs from 'fs';
import { CDPSession } from './Connection.js';
import { Protocol } from 'devtools-protocol';
import { CommonEventEmitter } from './EventEmitter.js';
import { assert } from './assert.js';
import { isNode } from '../environment.js';

export const debugError = debug('puppeteer:error');

Expand Down Expand Up @@ -309,9 +309,14 @@ async function readProtocolStream(
handle: string,
path?: string
): Promise<Buffer> {
if (!isNode && path) {
throw new Error('Cannot write to a path outside of Node.js environment.');
}

let eof = false;
let fileHandle: fs.promises.FileHandle;
let fileHandle: import('fs').promises.FileHandle;
if (path) {
const fs = await import('fs');
fileHandle = await fs.promises.open(path, 'w');
}
const bufs = [];
Expand All @@ -323,7 +328,10 @@ async function readProtocolStream(
response.base64Encoded ? 'base64' : undefined
);
bufs.push(buf);
if (path) await fs.promises.writeFile(fileHandle, buf);
if (path) {
const fs = await import('fs');
await fs.promises.writeFile(fileHandle, buf);
}
}
if (path) await fileHandle.close();
await client.send('IO.close', { handle });
Expand Down

0 comments on commit ded9c0f

Please sign in to comment.