Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

puppeteer - constructor issue in nestjs framework

I'm learning NestJs and puppeteer.

I tried web crawl and it worked well.

But because of launching and closing headless browser, it takes a lot of response time.

I think it's better launching browser just one time than every launching and closing.

But i don't know how i use constructor in NestJS. It looks different from Vanila javascript.

async crawlData() {
        const browser = await launch();
        const page = await browser.newPage();
        await page.goto("https://ko.reactjs.org/");
        await page.screenshot({ path: "./Docs/ko-reactjs-homepage.png" });
        await browser.close();
}

Please understand that i'm not native english speaker.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It sounds like you need a custom provider for the browser so it can be opened once and don't need to open it again. Something along the lines of

{
  provide: 'PUPPETEER_INSTNACE',
  useFactory: async () => await launch()
}

And now in a constructor in a service that belongs to same module you can do @Inject('PUPPETEER_INSTANCE') private readonly puppeteer)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...