Can not call another REST request in mongoose findOne() NodeJS - javascript

I'm newbie in NodeJS. I used Mongoose to check the existing item, if the item is not exist then will call another REST API, but it throw the error when running.
//check if hotel is existing
HotelModel.findOne({ name: hotel.name }, { name: 1 }, function (err, result) {
if (err) {
return
}
if (result) {
return
}
var address = await getHotelAddress(hotel.id) => throw error
});
and here is the error log:
var address = await getHotelAddress(hotel.id)
^^^^^^^^^^^^^^^
SyntaxError: Unexpected identifier
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:607:28)
at Object.Module._extensions..js (module.js:654:10)
It seems to can not call another task in findOne.
Thanks in advance.

Related

How to add information on a try catch error chain, for a comprehensive stack trace? [duplicate]

This question already has answers here:
JavaScript / TypeScript : Standard way to keep the cause of an Error
(3 answers)
Closed 3 months ago.
Taken this code:
try {
try {
try {
throw new Error(`ERR00`)
} catch (error) {
throw new Error(`ERR01`)
}
} catch (error) {
throw new Error(`ERR03`)
}
} catch (error) {
console.log(error, (error as Error).stack);
}
The stack output will only report the most external error (topmost) but not the error chain.
Now imagine this error chain happen on distinct places func03 calls func02 calls func01
otherwise solution might be simple and wrap everything on a single trycatch.
Stack will only report error for func03 and will not be straightforward to backtrace the error. Without additional logging.
Like:
Error: ERR00
at Object.<anonymous> (/[...]/test.ts:4:15)
at Module._compile (internal/modules/cjs/loader.js:1085:14)
at Module.m._compile (/usr/local/lib/node_modules/ts-node/src/index.ts:858:23)
at Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
at Object.require.extensions.<computed> [as .ts] (/usr/local/lib/node_modules/ts-node/src/index.ts:861:12)
at Module.load (internal/modules/cjs/loader.js:950:32)
at Function.Module._load (internal/modules/cjs/loader.js:790:12)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
at main (/usr/local/lib/node_modules/ts-node/src/bin.ts:227:14)
at Object.<anonymous> (/usr/local/lib/node_modules/ts-node/src/bin.ts:513:3) Error: ERR00
at Object.<anonymous> (/Users/nicola.aretini/Documents/github/nms-backend-services/nms.productful/test.ts:43:15)
at Module._compile (internal/modules/cjs/loader.js:1085:14)
at Module.m._compile (/usr/local/lib/node_modules/ts-node/src/index.ts:858:23)
at Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
at Object.require.extensions.<computed> [as .ts] (/usr/local/lib/node_modules/ts-node/src/index.ts:861:12)
at Module.load (internal/modules/cjs/loader.js:950:32)
at Function.Module._load (internal/modules/cjs/loader.js:790:12)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
at main (/usr/local/lib/node_modules/ts-node/src/bin.ts:227:14)
at Object.<anonymous> (/usr/local/lib/node_modules/ts-node/src/bin.ts:513:3)
How do you recommend to use Error class to fill up correctly the stack trace ?
To get something like:
Error: ERR03
at Object.<anonymous> (/[...]/test.ts:4:15)
Error: ERR02
at Object.<anonymous> (/[...]/test.ts:6:15)
Error: ERR01
at Object.<anonymous> (/[...]/test.ts:8:15)
....
This is what the .cause error property (see the old proposal page for more details) is meant to do:
try {
try {
try {
throw new Error(`ERR00`)
} catch (error) {
throw new Error(`ERR01`, {cause: error})
}
} catch (error) {
throw new Error(`ERR03`, {cause: error})
}
} catch (error) {
console.error(error);
}

cant catch code breaking error thrown inside required class

im trying to scrap a website using pupeteer , this website has captcha and i use a 3rd party library/api to bypass the captcha
here is the simplified version of my code
const puppeteer = require('puppeteer');
const dbc = require('./dpc/deathbycaptcha');
async function init()
{
let page = launchPuppeteer();
try {
await page.goto(`https://www.example.com`, {timeout: 60000});
await captcha_element.screenshot({ path: setting.captcha , omitBackground: true, });
let captchaResult = await solve_captcha().catch((error)=> {throw new Error( error) });
log('ALL DONE');
}
catch (e) {
log('=====================ERROR============================');
log(e);
}
}
here is solve_captcha function
function solve_captcha(){
return new Promise(( resolve , reject )=>{
try
{
const client = new dbc.HttpClient('myUsername', 'myPassword');
client.decode({captcha: setting.captcha}, (captcha) => {
if (captcha) {
resolve(captcha['text']);
}
else
{
reject('error')
}
});
}
catch (e) {
reject(e.toString());
}
})
}
so sometimes i cant connect to captcha solving api due to down server or network problems , it would throw this error
C:\pathToProject\dpc\deathbycaptcha.js:218
throw new Error(err.message);
^
Error: read ECONNRESET
at ClientRequest.<anonymous> (C:\pathToProject\dpc\deathbycaptcha.js:218:15)
←[90m at ClientRequest.emit (events.js:310:20)←[39m
←[90m at Socket.socketErrorListener (_http_client.js:426:9)←[39m
←[90m at Socket.emit (events.js:310:20)←[39m
←[90m at emitErrorNT (internal/streams/destroy.js:92:8)←[39m
←[90m at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)←[39m
←[90m at processTicksAndRejections (internal/process/task_queues.js:84:21)←[39m
this error happens in the deathbycaptcha.js which i've required in my code with
const dbc = require('./dpc/deathbycaptcha');
here is the simplified version of the code in the in the deathbycaptcha.js which is cuzing the error
class HttpClient extends Client {
_call(arguments here) {
var options = {someoptions};
var form = new FormData();
const request = form.submit(options, (err, response) => {
if (err) {
console.log(err.toString())
throw new Error(err.message);
}
// more code here
}
}
so here is the problem , i have this code running inside 2 try/catch blocks
first in the caller function (init()) and second one in the solve_captcha function but none of them are able to catch this error and it will break all the code and the program will exit and i have to run it again
why cant i catch and handle this error in my code ?

nodeJS returns Type Error when creating a file using fs writeFile

I've just started learning nodeJS. I'm at a very basic level.
Right now I'm working with creating new files and directories methods.
This is my Code -
var fs = require('fs');
fs.mkdir("stuff", function () {
fs.readFile('readMe.txt', 'utf8', function (err, data){
fs.writeFile('./stuff/writeMe.txt', data);
});
});
It does create the directory and does read the file, but doesn't create a new file.
I checked the code times and again, but the terminal is returning this error.
fs.js:152
throw new ERR_INVALID_CALLBACK(cb);
^
TypeError [ERR_INVALID_CALLBACK]: Callback must be a function. Received undefined
[90m at maybeCallback (fs.js:152:9)[39m
[90m at Object.writeFile (fs.js:1351:14)[39m
at D:\PRANAV\Learning Folder\Node\app.js:6:12
[90m at FSReqCallback.readFileAfterClose [as oncomplete] (internal/fs/read_file_context.js:63:3)[39m {
code: [32m'ERR_INVALID_CALLBACK'[39m
}
I'm stuck at this, please help.
fs.writeFile's last argument should be a callback function. Right now, you're missing it:
fs.mkdir("stuff", function () {
fs.readFile('readMe.txt', 'utf8', function (err, data) {
fs.writeFile('./stuff/writeMe.txt', data, function (err) {
if (err) {
throw err;
}
console.log('written successfully!');
});
});
});

How to setup Braintree API in node js?

I want use braintree for website paymentgateway, unfortunately when I follow the guideline online, & the code unable to be use in node js. Is anything missing?
Index.js:
//send token to clients
app.get("/client_token", function (req, res) {
gateway.clientToken.generate({}, function (err, response) {
res.send(response.clientToken);
});
});
//Receive payment from clients
app.post("/checkout", function (req, res) {
var nonceFromTheClient = req.body.payment_method_nonce;
// Use payment method nonce here
});
//Test sandbox
gateway.transaction.sale({
amount: "10.00",
paymentMethodNonce: nonceFromTheClient,
options: {
submitForSettlement: true
}
}, function (err, result) {
if (err) {
console.error(err);
return;
}
if (result.success) {
console.log('Transaction ID: ' + result.transaction.id);
} else {
console.error(result.message);
}
});
Error unable pass the node js npm start:
paymentMethodNonce: nonceFromTheClient,
Details in IDE:
ReferenceError: nonceFromTheClient is not defined
at Object.<anonymous> (/Users/desmondkam/codecampvn/index.js:37:23)
at Module._compile (module.js:541:32)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:456:32)
at tryModuleLoad (module.js:415:12)
at Function.Module._load (module.js:407:3)
at Function.Module.runMain (module.js:575:10)
at startup (node.js:160:18)
at node.js:445:3
Solved
Remove //Test sandbox part would solve the problem of compiled normal in localhost & IDE.
Inorder to running with Sandbox, would required some add-on code regarding: https://developers.braintreepayments.com/reference/general/testing/node:
"fake-valid-nonce"
Your code would be:
gateway.transaction.sale({
amount: "10.00",
paymentMethodNonce: "fake-valid-nonce",
options: {
submitForSettlement: true
}
}, function (err, result) {
});
In case someone is searching for a solution,
import braintree, {
BraintreeGateway,
KeyGatewayConfig,
ValidatedResponse,
Transaction,
ClientToken,
TransactionRequest
} from 'braintree';
import { ITransactionResponse } from '../components/payment/payment.types';
export default class BraintreeWrapper {
private gateway: BraintreeGateway;
constructor() {
// get the braintree key gateway config from environment, which we set in global environment objecr
const env: KeyGatewayConfig = environment.braintree;
// creates a gateway instance using
this.gateway = new braintree.BraintreeGateway(env);
}
// generate the client token
public async generateToken(): Promise < string > {
const result : ValidatedResponse < ClientToken > = await this.gateway.clientToken.generate({});
const { clientToken } = result;
return clientToken;
}
// make transaction
public async transaction(request: TransactionRequest): Promise < ITransactionResponse > {
const result: ValidatedResponse < Transaction > = await this.gateway.transaction.sale(request);
// extract transaction response keys from result
const {
transaction: {
id,
status,
type,
currencyIsoCode,
amount,
merchantAccountId,
orderId,
createdAt,
updatedAt,
}
} = result;
// map transaction response keys
const response: ITransactionResponse = {
id,
status,
type,
currencyIsoCode,
amount,
merchantAccountId,
orderId,
createdAt,
updatedAt,
};
return response;
}
}
I have created a guide to help you get started with the implementation
Integrate Braintree Payment Gateway SDK in Node.js and React

How to send data to USB device in node.js using libusb

I have try to get data from device (USB thermometer), following this documentation, but I have not any result.
For getting themperature data from device, I should send the data like that 'd\n'.
This is my code:
var usb = require('usb'),
term = usb.findByIds(65535, 2);
term.open();
var endpoints = term.interfaces[0].endpoints,
inEndpoint = endpoints[0],
outEndpoint = endpoints[1];
inEndpoint.transferType = 2;
inEndpoint.startStream(1, 64);
inEndpoint.transfer(64, function (error, data) {
if (!error) {
console.log(data);
} else {
console.log(error);
}
});
inEndpoint.on('data', function (data) {
console.log(data);
});
inEndpoint.on('error', function (error) {
console.log(error);
});
outEndpoint.transferType = 2;
outEndpoint.startStream(1, 64);
outEndpoint.transfer(new Buffer('d\n'), function (err) {
console.log(err);
});
After running I have got this:
D:\Dev\USBTest\node_modules\usb\usb.js:261
t.submit(new Buffer(self.streamTransferSize), transferDone)
^
Error: LIBUSB_ERROR_NOT_FOUND
at startTransfer (D:\Dev\USBTest\node_modules\usb\usb.js:261:5)
at Array.forEach (native)
at InEndpoint.startStream (D:\Dev\USBTest\node_modules\usb\usb.js:264:23)
at D:\Dev\USBTest\app.js:15:16
at Object.<anonymous> (D:\Dev\USBTest\app.js:35:2)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
You forgot to call interface.claim().
https://github.com/nonolith/node-usb#claim
The interface should be declared using the term.interface(interfaceId) method, not term.interfaces[0]
https://www.npmjs.com/package/usb#interfaceinterface
Use sudo before running your command.
Wrong:
node index.js
Right:
sudo node inex.js

Categories

Resources