1

My JS file "login.js" can be run from the command line with "node login.js". If I want to change the URL used I have to go into the file and edit the URL.

I'd like to be able to pass the URL as an argument via the command line, eg "node login.js https://example.com" and for the code to use that URL. I assume this is fairly straightforward but I can't seem to work it out from reading about it online.

const puppeteer = require('puppeteer');
const C = require('./constants');
const USERNAME_SELECTOR = '#email';
const PASSWORD_SELECTOR = '#password';
const CTA_SELECTOR = '#next';
const CTA_SELECTOR2 = '#submit-btn';


async function startBrowser() {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  return {browser, page};
}


async function closeBrowser(browser) {
  return browser.close();
}

async function playTest(url) {
  const {browser, page} = await startBrowser();
  page.setViewport({width: 1366, height: 768});
  await page.goto(url);
  await page.waitForSelector(USERNAME_SELECTOR);
  await page.click(USERNAME_SELECTOR);
  await page.keyboard.type(C.username);
  await page.click(CTA_SELECTOR);
  console.log('before waiting');
await delay(10000);
console.log('after waiting');
  await page.click(PASSWORD_SELECTOR);
  await page.keyboard.type(C.password);
  await page.click(CTA_SELECTOR2);
  await page.waitForNavigation();
  await page.screenshot({path: 'screenshot.png'});
}

(async () => {
  await playTest("https://example.com");
  process.exit(1);
})();

function delay(time) {
  return new Promise(function(resolve) { 
      setTimeout(resolve, time)
  });
}
Quirkless
  • 55
  • 1
  • 5
  • How 'bout this? https://stackoverflow.com/a/4351548/1024832 – Marc Aug 09 '20 at 17:15
  • Or this? [How do I pass command line arguments to a Node.js program?](https://stackoverflow.com/questions/4351521/how-do-i-pass-command-line-arguments-to-a-node-js-program) – Marc Aug 09 '20 at 17:16
  • Thanks for the reply. I did read this before posting but I couldn't make sense of it. I'll try reading it again. – Quirkless Aug 09 '20 at 17:20

1 Answers1

1

In many programs (including node), arguments can be passed to your script through something we call flags.

Node itself is a program and when you write node foo.js, foo.js itself is an argument to the node program. To pass arguments through command line use flags via double dash.

Example:

node foo.js bar/baz/index.html 

now the value can be accessed through process.argv which is an array of all the arguments passed to it. It will look something like this

['node.exe', 'foo.js', 'bar/baz/indez.html']
natzelo
  • 66
  • 7
  • Thanks. Does that mean in my case I could use "node login.js --url="https://example.com" And edit my code so... (async () => { await playTest("URL"); process.exit(1); })(); But then do I need to add a URL const? – Quirkless Aug 09 '20 at 17:26
  • 1
    use `process.argv[2]` to get the string value – natzelo Aug 09 '20 at 18:23