How to limit cpu usage with Nodejs?

I want to introduce the node-cpulimit in this post.When i use puppeteer ,some page cost a long time in page loading. At the same time , the cpu limit will increase instantly.So i want to find some tools to help limit the cpu usage.

A very simple example to use cpulimit and childprocess

const limiter = require('cpulimit');


// Run command
const { spawn } = require('child_process');
const node = spawn('node', ['/root/puppeteer.js']);



// Run cpulimit
const options = {
  limit: 50, // or any other value
  includeChildren: true,
  pid: node.pid
};

limiter.createProcessFamily(options, (err, processFamily) => {
  if (err) {
    console.error('Error:', err.message);
    return;
  }

  limiter.limit(processFamily, options, (err) => {
    if (err) {
      console.error('Error:', err.message);
    } else {
      console.log('Done.');
    }
  });
});

for more detail pls visit

https://github.com/vangelov/node-cpulimit

Run puppeteer in Heroku free node!

$ cd xx # cd in you git repository
$ heroku login -i # login heroku
$ heroku create  # create a free node
$ heroku buildpacks:add --index 1 heroku/nodejs
$ heroku buildpacks:add --index 2 https://github.com/heroku/heroku-buildpack-google-chrome.git
$ git add .
$ git commit -m "init commit"
$ git push heroku master
# push you code to the apps and it will auto build the chrome environment and run you puppeteer code!

# login to the heroku website and start the worker dyno(by default the worker dyno is disable)

Some tips for Puppeteer

1.Type some text into input tags

await page.type('input.form-control[placeholder="Your Email"]',"something you want to input",{delay:500});

the code show above will type “something you want to input” into the <input class=”form-control” placeholder=”Your Email”>

2.Simulate button click

await page.click('input[value="Login"]');

the code show above will click the
<input value=”Login”>

3. Tabs control (Switch foreground and background)

const allPages = await browser.pages(); // get all the tabs in browser
await allPages[1].bringToFront();       
// select 1 and bring it to foreground , notice ! allPages[0] always be a blank page created by puppeteer

4. Simulate keyboard input

await page.keyboard.press('ArrowDown'); 

5. Others

$$ select all the match element and $ just select the first one!


for more detail visit the puppeteer api document!


https://github.com/GoogleChrome/puppeteer/blob/v1.14.0/docs/api.md#pageselector