How can I assing current url to a variable? NodeJS Selenium-webdriver - node.js

How can I assing current url or current title to a variable
let isRedirected = driver.getCurrentUrl()
console.log(isRedirected)
if (isRedirected = 'https://www.xxxx.com//redirect_main.html') {
await spinner.succeed(chalk.green(`Success: ${chalk.blue(line[0])}`));
} else {console.log('err')}
when i tried with this code i got
output:
Promise { <pending> }
and i tried it for currentTitle and i got same output, where is my fault

Related

No Response when calling FIDE-Ratings-Scraper NPM Package in JavaScript

I have used npm to install this package: https://github.com/xRuiAlves/fide-ratings-scraper using npm i fide-ratings-scraper. I use node to run a script with the following code in it:
var fideRatingsScraper = require("fide-ratings-scraper")
//Danii Dubov's FIDE player id: 24126055
console.log(fideRatingsScraper)
var fullInfo = fideRatingsScraper.getPlayerFullInfo('24126055');
console.log(fullInfo)
I get a response that shows that some code is executing. For the line where I print the variable fideRatingsScraper I get:
{
getPlayerFullInfo: [AsyncFunction: getPlayerFullInfo],
getPlayerElo: [AsyncFunction: getPlayerElo],
getPlayerHistory: [AsyncFunction: getPlayerHistory],
getPlayerRank: [AsyncFunction: getPlayerRank],
getPlayerPersonalData: [AsyncFunction: getPlayerPersonalData]
}
When I try to print out the variable fullInfo terminal prints out:
Promise { <pending> }
What am I missing here? I want to get the fullInfo for any player ID I list; I seem to be missing something simple.

Playwright pass variable into eval with JavaScript (Node)

Note: this is for Playwright, the browser API, like puppeteer.
I'm trying to find all elements on a page, then want to filter those elements down into values.
The values have specific selectors on them (css classes, etc).
The problem I have is that I cannot pass outside variables into the $$eval function so that my CSS selectors can be dynamic.
EG:
const cardsPerPage = await page.$$eval('.ais-hits--item', (repoCards) => {
return repoCards.map(card => {
const name = card.querySelector('a.product-thumbnail__title'); // < this is the problem
return {
name: toText(name),
};
});
});
If I try to change my CSS selector to a variable it doesn't work, I've tried just about everything.
const customSelector = 'a.product-thumbnail__title';
const cardsPerPage = await page.$$eval('.ais-hits--item', (repoCards) => {
return repoCards.map(card => {
const name = card.querySelector(customSelector); // < this is the problem
return {
name: toText(name),
};
});
});
The error is:
error: page.$$eval: ReferenceError: customSelector is not defined
at eval (eval at evaluate (:3:2389), <anonymous>:4:57)
at Array.map (<anonymous>)
at eval (eval at evaluate (:3:2389), <anonymous>:2:38)
at t.default.evaluate (<anonymous>:3:2412)
at t.default.<anonymous> (<anonymous>:1:44)
at Scraper.main (/home/steve/dev/test/src/scraper/index.js:67:49)
You'll need to do something like
const customSelector = 'a.product-thumbnail__title';
const cardsPerPage = await page.$$eval('.ais-hits--item', (repoCards, selector) => { // Your selector from ➀ becomes the last param of your evaluated lambda
return repoCards.map(card => {
const name = card.querySelector(selector);
return {
name: toText(name),
};
});
}, customSelector); // ➀ Your selector is passed in as the arg param
Additionally, if toText was declared outside of $$eval which it seems to be, then you'll get an error for that, too.

TypeError: invNum.next is not a function

I have tried this code :
const invNum = require('invoice-number');
router.post('/checkout', async (req, res, next) => {
if (!req.session.cart) {
return res.redirect('/pos/');
}
var saleList = Sale.find().sort({ _id: -1 }).limit(1); // removed (err, data)=>{} to simply view it is working tested already
var settings = await Setting.find({}); // removed try and catch to simply view it is working tested already
var ticketNumber;
ticketNumber = !saleList ? invNum.next('0000000') : invNum.next(saleList.ticket_number);
var sale = new Sale({
ticket_number:ticketNumber,
cart: req.session.cart,
created_at: new Date()
});
sale.save((err, product) => {
createReceipt(settings, req.session.cart, "receipts/"+ticketNumber+".pdf");
req.session.cart = null;
res.redirect('/pos/');
});
});
I got this error:
TypeError: invNum.next is not a function
The problem is with invNum.next().
invNum.next() is a Node.js module to generate invoice number sequentially installed from npm.
Example:
invNum.next('2017/08/ABC001')
// => 2017/08/ABC002
I have tried already suggestions from previous stackoverflow posts by trying Promises or await async function in order to get this code to work. Hopefully, you can help or suggest something. Thank you.
There is a problem in version of invoice-number module. In the npm it is showing as 1.0.6 but in the GitHub repository it has 1.0.5 in the package.json file.
https://github.com/amindia/invoice-number.
I have tested this module by taking from Github repository and it's working fine.
Please take the source of this module from the given link it will works fine.
Seems to be some error in the module. I tried the below code snippet on RunKit
https://runkit.com/embed/ws2lv1y38mt4
var invNum = require('invoice-number')
try{
invNum.next('sdfsd1')
} catch(e){
console.log(e)
}
Getting the same error
I got this error:
TypeError: invNum.next is not a function UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch()
What is the output when you use the console.log on invNum?
Also use try catch and inside call invNum.next with await. Maybe something inside this function is throwing an error.
Edit: as jfriend00 says, if an plain text (like your "0000...") is working, probably the saleList is returning some error and you are not catching or treating the error.
Edit2: The last update on this NPM code is from 1 year ago and fewer people used this lib, probably is broken.
There is some part of the code from the index.js of the lib:
function _next (invoiceNumber) {
if (!invoiceNumber)
throw new Error('invoiceNumber cannot be empty')
var array = invoiceNumber.split(/[_/:\-;\\]+/)
var lastSegment = array.pop()
var priorSegment = invoiceNumber.substr(0, invoiceNumber.indexOf(lastSegment))
var nextNumber = alphaNumericIncrementer(lastSegment)
return priorSegment + nextNumber}
var api = { next: _next}
module.exports = api

Undefined property when unit testing my discord.js bot (the test itself is passed, but it is followed by an error)

I am trying to set up unit testing for my discord.js bot, but when running npm test in the terminal, while the test is being passed, still gives an error.
This is an image of the test being passed followed by the error:
https://i.imgur.com/m2EOuxc.png
I need to fix this error in testing, while still having the bot being able to function.
I have tried to completely remove the line referenced in the error (and the lines that had something to do with that specific line)
jsfiles.forEach((f, i) => {
let props = require(`./cmds/${f}`)
bot.commands.set(props.help.name, props)
})
Removing this resolved the testing issue, but resulted in the bot not functioning correctly (it did not load the commands; meaning, the bot couldn't be interacted with), which is not the goal here.
I've also checked, that each of the files in the folder cmds ends with
module.exports.help = {
name: '<name of the command I use for each command>'
}
This is the part of my bot.js file that contains the problem.
// Loads the commands for the bot:
fs.readdir('./cmds/', (err, files) => {
if (err) console.error(err)
let jsfiles = files.filter(f => f.split('.').pop() === 'js')
if (jsfiles.length <= 0) {
console.log('No commands to load!')
return
}
if (testingSettings) {
console.log(`Loading ${jsfiles.length} commands!`)
}
// This is the problem referenced above:
// ----------------------------------------------------------------------
jsfiles.forEach((f, i) => {
let props = require(`./cmds/${f}`)
bot.commands.set(props.help.name, props)
})
// ----------------------------------------------------------------------
})
This is all of my code in the bot.test.js file
const {
// Functions
checkingTesting,
// Variables
testingSettings,
} = require('./bot')
test('checking to see if testing-mode is on', () => {
expect(checkingTesting(testingSettings, 'token')).toBe(process.env['token']);
});
If it is needed. This is the function, variable and exporting method that is used to connect bot.js to bot.test.js:
Variable (in bot.js file)
const testingSettings = false
Function (in bot.js file)
function checkingTesting (testingSettings, name) {
if (testingSettings) {
return testSettings[name]
} else if (!testingSettings) {
return process.env[name]
}
}
Exporting (in bot.js file)
module.exports = {
// Exporting functions
checkingTesting: checkingTesting,
// Exporting variables
testingSettings: testingSettings,
}
props.help is undefined. The required file's exported obj is either empty, doesn't have help, or some other unforeseen event.
A good practice is to always check whether an object key exist prior using it.
if (props && props.help) {
bot.commands.set(props.help.name, props)
} else {
//throw or handle error here
}
In your command file, it seems like there is no help property of module.exports. When you try to read help.name, it throws your error because help is undefined.
Check to make sure that you're declaring module.exports.help in every command file.

How to access variable in another file in node js

I have 2 files: export.js and server.js
I'm trying to access a variable in export.js in server.js, but I get undefined.
Note that I'm using knexjs and I gave it the name 'db';
export.js
let count;
const livePending = (db) => {
db('cart')
.count('id').where('status','=','Pending')
.then(data => {
if (data[0]) {
count = data[0].count;
}
}).catch(err => res.status(400).send('DB Connection failed!'));
}
module.exports = {
livePending: livePending,
pCount: count
}
server.js
[...]
const anotherFile = require('./export');
anotherFile.livePending(db);
console.log(import.pCount);
When I try to console log inside the livePending function in export.js, I get the desired count which is 1.
The reason I'm doing this is to lessen the lines of code in my server.js.
If I do the exact same function in my server.js, I get the correct result.
I created a small node app to test a variation of your code. Two important findings:
1.
const import = require('./export');
import is reserved (as well as export). Node will throw a SyntaxError: Unexpected token if you attempt to use either one as a variable name.
2.
console.log(import.count);
In your code, you're attempting to log a variable that's already been returned. You'll notice the log statement will return undefined. Instead, create a function that you can call to get the value from the actual variable in the other file.
To make things clearer, here's a little demo to show these concepts in action.
export.js
let count;
const setCount = num => count = num;
const getCount = () => count;
// Shortcut: If the key: value is the same, we can just omit the value
module.exports = {
setCount,
getCount
}
server.js
const ex = require('./export');
ex.setCount(5);
console.log(ex.getCount()); // 5

Resources