Quirkless
Quirkless

Reputation: 65

How can I pass an argument into my Javascript code from command line?

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)
  });
}

Upvotes: 2

Views: 3279

Answers (1)

natzelo
natzelo

Reputation: 66

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']

Upvotes: 1

Related Questions