[英]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".我的 JS 文件“login.js”可以使用“node login.js”从命令行运行。 If I want to change the URL used I have to go into the file and edit the URL.如果我想更改使用的 URL,我必须将 go 更改为文件并编辑 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.我希望能够通过命令行将 URL 作为参数传递,例如“node login.js https://example.com”以及使用该 ZE6B391A8D2C4D45902A23A8 的代码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)
});
}
In many programs (including node), arguments can be passed to your script through something we call flags.在许多程序(包括节点)中,arguments 可以通过我们称为标志的东西传递给您的脚本。
Node itself is a program and when you write node foo.js
, foo.js
itself is an argument to the node program. Node 本身是一个程序,当您编写node foo.js
时, foo.js
本身就是 node 程序的参数。 To pass arguments through command line use flags via double dash.要通过命令行传递 arguments,请通过双破折号使用标志。
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.现在可以通过process.argv
访问该值,它是传递给它的所有 arguments 的数组。 It will look something like this它看起来像这样
['node.exe', 'foo.js', 'bar/baz/indez.html']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.