There Is My Code ~
const user = new User(req.body, rules);
const matched = await user.check();
if (!matched) {
return res.status(404).send(user.errors)
}
I'm fairly new to Node.js and I am having some issues.
May I know what is wrong with my code?
Related
I'm trying to get the current block number from Binance Smart Chain (BSC).
In the documentation, provider.getBlockNumber() returns a Promise object.
Here are my attempts to consume and print the current block number into console.
I'm using Node.js v16.5.0 and Ethers.js 5.4.1.
var ethers = require("ethers");
var url = "wss://bsc-ws-node.nariox.org:443";
const provider = new ethers.providers.WebSocketProvider(url);
const blockNumber = async function() {
return await provider.getBlockNumber();
}
console.log(blockNumber());
process.exit();
This returns Promise { <pending> } on the console.
This block of code:
var ethers = require("ethers");
var url = "wss://bsc-ws-node.nariox.org:443";
const provider = new ethers.providers.WebSocketProvider(url);
async function blockNumber() {
const blockNumber = await provider.getBlockNumber();
return blockNumber();
}
blockNumber().then(data => {console.log(data)});
process.exit();
output exactly nothing in the console, almost as there's nothing wrong in the code.
Expected output should be a number, like 9380976.
Where did I go wrong?
EDIT 1: Added process.exit() because that's supposed to be in the original post.
ANSWER by #purple:
var ethers = require("ethers");
var url = "wss://bsc-ws-node.nariox.org:443";
const provider = new ethers.providers.WebSocketProvider(url);
async function blockNumber() {
const blockNumber = await provider.getBlockNumber();
return blockNumber;
}
blockNumber().then(data => {
console.log(data)
process.exit();
});
Result:
> node app
*pauses for a bit, then prints*
9397167
>
Did you mean return blockNumber; instead of return blockNumber();?
const Web3 = require('web3');
const fs = require('fs')
const web3 = new Web3("http://localhost:7545");
const contract_address = "0x7484d32e891817702c5d7c764dBF7e592000b415";
async function web3Contract() {
const contract_abi = fs.readFileSync('./build/contracts/Bottle.json', 'utf8')
const Bottle = await new web3.eth.Contract(JSON.parse(contract_abi).abi, contract_address);
Bottle.methods.setName("Palm").send();
Bottle.methods.getGreeting().call();
}
async function run() {
try {
await web3Contract();
} catch (err) {
console.log('Your error is this - ' + err);
}
}
run();
I'm getting a error "UnhandledPromiseRejectWarning". I been googling this for hours and can't seem to fix this. Please guide me in the right direction. Thank you.
Pointer 1: Don't evaluate JSON.parse(contract_abi).abi as a parameter. If you do there is no way checking what it is - and it is possibly causing the error. Better:
const contract_abi = fs.readFileSync('./build/contracts/Bottle.json', 'utf8');
const abi = JSON.parse(contract_abi).abi;
console.log( abi); // do you get this far?
const Bottle = await new web3.eth.Contract(abi, contract_address);
Pointer 2: Don't log the string value of an error object when debugging - you will only get its toString() result which looks to be the same as logging error.message. Better:
console.log('Your error is this - ', err);
Supplying err as a second argument causes node to log additional properties of the error object including error.stack which provides trace information.
I am using Spark AR to create a simple effect that grabs text from an api and displays it.
Here is my code
const Scene = require('Scene');
const Diagnostics = require('Diagnostics');
const Patches = require('Patches');
const Textures = require('Textures');
const Materials = require('Materials');
const Networking = require('Networking');
const URL = 'https://gabby-airbus.glitch.me/random';
Networking.fetch(URL).then(function(result){
if( (result.status >=200) && (result.status < 300)){ return result.json(); }
else { throw new Error('HTTP Status Code: ' + result.status); }
}).then(function(json){
// show json data in console
Diagnostics.log(json.item);
// Asign json data to text object
itemText.text = json.item;
}).catch(function(error){
itemText = 'Failed to start';
Diagnostics.log(result.status + error);
});
I get the following error
Error:Cannot read property 'fetch' of undefined
{
"line": 12,
"column": 17,
"sourceURL": "script.js"
}
I am not sure why i am getting undefined when https://gabby-airbus.glitch.me/random is clearly not undefined. it has a random json object.
I am following the solution suggested in this SO post
Currently it is not possible, the Networking capability is disabled for security reasons. There is a plan to have it back soon though.
https://sparkar.facebook.com/ar-studio/learn/reference/classes/networkingmodule
I am fairly new to JS/Winappdriver.
The application I am trying to test is a windows based "Click Once" application from .Net, so I have to go to a website from IE and click "Install". This will open the application.
Once the application is running, I have no way to connect the application to perform my UI interactions while using JavaScript.
Using C#, I was looping through the processes looking for a process name, get the window handle, convert it to hex, add that as a capability and create the driver - it worked. Sample code below,
public Setup_TearDown()
{
string TopLevelWindowHandleHex = null;
IntPtr TopLevelWindowHandle = new IntPtr();
foreach (Process clsProcess in Process.GetProcesses())
{
if (clsProcess.ProcessName.StartsWith($"SomeName-{exec_pob}-{exec_env}"))
{
TopLevelWindowHandle = clsProcess.Handle;
TopLevelWindowHandleHex = clsProcess.MainWindowHandle.ToString("x");
}
}
var appOptions = new AppiumOptions();
appOptions.AddAdditionalCapability("appTopLevelWindow", TopLevelWindowHandleHex);
appOptions.AddAdditionalCapability("ms:experimental-webdriver", true);
appOptions.AddAdditionalCapability("ms:waitForAppLaunch", "25");
AppDriver = new WindowsDriver<WindowsElement>(new Uri(WinAppDriverUrl), appOptions);
AppDriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(60);
}
How do I do this in Javascript ? I can't seem to find any code examples.
Based on an example from this repo, I tried the following in JS to find the process to latch on to but without luck.
import {By2} from "selenium-appium";
// this.appWindow = this.driver.element(By2.nativeAccessibilityId('xxx'));
// this.appWindow = this.driver.element(By2.nativeXpath("//Window[starts-with(#Name,\"xxxx\")]"));
// this.appWindow = this.driver.elementByName('WindowsForms10.Window.8.app.0.13965fa_r11_ad1');
// thisappWindow = this.driver.elementByName('xxxxxxx');
async connectAppDriver(){
await this.waitForAppWindow();
var appWindow = await this.appWindow.getAttribute("NativeWindowHandle");
let hex = (Number(ewarpWindow)).toString(16);
var currentAppCapabilities =
{
"appTopLevelWindow": hex,
"platformName": "Windows",
"deviceName": "WindowsPC",
"newCommandTimeout": "120000"
}
let driverBuilder = new DriverBuilder();
await driverBuilder.stopDriver();
this.driver = await driverBuilder.createDriver(currentEwarpCapabilities);
return this.driver;
}
I keep getting this error in Winappdriver
{"status":13,"value":{"error":"unknown error","message":"An unknown error occurred in the remote end while processing the command."}}
I've also opened this ticket here.
It seems like such an easy thing to do, but I couldn't figure this one out.
Any of nodes packages I could use to get the top level window handle easily?
I am open to suggestions on how to tackle this issue while using JavaScript for Winappdriver.
Hope this helps some one out there,
Got around this by creating an exe using C# that generated hex of the app to connect based on the process name, it looks like something like this.
public string GetTopLevelWindowHandleHex()
{
string TopLevelWindowHandleHex = null;
IntPtr TopLevelWindowHandle = new IntPtr();
foreach (Process clsProcess in Process.GetProcesses())
{
if (clsProcess.ProcessName.StartsWith(_processName))
{
TopLevelWindowHandle = clsProcess.Handle;
TopLevelWindowHandleHex = clsProcess.MainWindowHandle.ToString("x");
}
}
if (!String.IsNullOrEmpty(TopLevelWindowHandleHex))
return TopLevelWindowHandleHex;
else
throw new Exception($"Process: {_processName} cannot be found");
}
Called it from JS to get the hex of the top level window handle, like this,
async getHex () {
var pathToExe =await path.join(process.cwd(), "features\\support\\ProcessUtility\\GetWindowHandleHexByProcessName.exe");
var pathToDir =await path.join(process.cwd(), "features\\support\\ProcessUtility");
const result = await execFileSync(pathToExe, [this.processName]
, {cwd: pathToDir, encoding: 'utf-8'}
, async function (err, data) {
console.log("Error: "+ err);
console.log("Data(hex): "+ data);
return JSON.stringify(data.toString());
});
return result.toString().trim();
}
Used the hex to connect to the app like this,
async connectAppDriver(hex) {
console.log(`Hex received to connect to app using hex: ${hex}`);
const currentAppCapabilities=
{
"browserName": '',
"appTopLevelWindow": hex.trim(),
"platformName": "Windows",
"deviceName": "WindowsPC",
"newCommandTimeout": "120000"
};
const appDriver = await new Builder()
.usingServer("http://localhost:4723/wd/hub")
.withCapabilities(currentAppCapabilities)
.build();
await driver.startWithWebDriver(appDriver);
return driver;
}
Solution:
In WebDriverJS (used by selenium / appium), use getDomAttribute instead of getAttribute. Took several hours to find :(
element.getAttribute("NativeWindowHandle")
POST: /session/270698D2-D93B-4E05-9FC5-3E5FBDA60ECA/execute/sync
Command not implemented: POST: /session/270698D2-D93B-4E05-9FC5-3E5FBDA60ECA/execute/sync
HTTP/1.1 501 Not Implemented
let topLevelWindowHandle = await element.getDomAttribute('NativeWindowHandle')
topLevelWindowHandle = parseInt(topLevelWindowHandle).toString(16)
GET /session/DE4C46E1-CC84-4F5D-88D2-35F56317E34D/element/42.3476754/attribute/NativeWindowHandle HTTP/1.1
HTTP/1.1 200 OK
{"sessionId":"DE4C46E1-CC84-4F5D-88D2-35F56317E34D","status":0,"value":"3476754"}
and topLevelWindowHandle have hex value :)
I am just trying a simple get command with Firestore, using this code from Google it doesn't work because it's not waiting for the promise?
Earlier I had put only a snippet of code, this is the entirety of index.js -- I'm using Firestore with Dialogflow to build a Google Assistant app and trying to call a function from the welcome intent that gets a field from Firestore, then writes that field to a string (named question1), and then this string should be spoken by the assistant as part of the ssml response. I've been on this for at least 30 hours already, can't seem to comprehend promises in regards to intents, firestore, etc. I've tried about 10 different solutions, this one works, only it says "undefined" in other variations I have tried it would say undefined several times but after 2-3 passes the get command would be complete and then the variable would be read out. I'm just trying to figure out how to get the get command and variable set before moving onto the SSML response. Can anyone point me in the right direction?
'use strict';
const functions = require('firebase-functions'); //don't forget this one
// Import Admin SDK
var admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);
var db = admin.firestore();
const collectionRef = db.collection('text');
const Firestore = require('#google-cloud/firestore');
var doc;
var question1;
const url = require('url');
const {
dialogflow,
Image,
Permission,
NewSurface,
} = require('actions-on-google');
const {ssml} = require('./util');
const config = functions.config();
const WELCOME_INTENT = 'Default Welcome Intent';
const app = dialogflow({debug: true});
async function dbaccess(rando) {
console.log("dbaseaccess started")
var currentquestion2 = 'question-' + rando.toString();
var cityRef
try { return cityRef = db.collection('text').doc(currentquestion2).get();
console.log("get command completed")
//do stuff
question1 = cityRef.data().n111
} catch(e) {
//error!
}
console.log("one line above return something");
return rando;
}
app.fallback((conv) => {
// intent contains the name of the intent
// you defined in the Intents area of Dialogflow
const intent = conv.intent;
switch (intent) {
case WELCOME_INTENT:
var rando = Math.floor(Math.random() * 3) + 1;
dbaccess(rando);
const ssml =
'<speak>' +
question1 +
'</speak>';
conv.ask(ssml);
break;
exports.dialogflowFirebaseFulfillment = functions.https.onRequest(app);
You have 2 options: you can use async/await or you can use Promise.then() depending on how you want the code to execute.
Async/await:
async function databasetest {
var cityRef;
try{
cityRef = await db.collection('cities').doc('SF');
// do stuff
} catch(e) {
// error!
}
Promise.then():
db.collection('cities').doc('SF').then((cityRef) => {
cityRef.get()
.then(doc => { /* do stuff */ })
.catch(err => { /* error! */ });
});
maybe a little of work around could help you, I'm not sure yet how you are trying to implement it.
function databasetest () {
var cityRef = db.collection('cities').doc('SF');
return cityRef.get()
}
// so you can implement it like
databasetest().then(doc => {
if (!doc.exists) {
console.log('No such document!');
} else {
console.log('Document data:', doc.data());
}
})
.catch(err => {
console.log('Error getting document', err);
});
More context would help to understand your use case better :)