web3, truffle, nodejs error : UnhandledPromiseRejectionWarning - node.js

var web3 = require('web3'),
contract = require('truffle-contract'),
path = require('path'),
MyContractJSON = require(path.join(__dirname, '../tru_dir/build/contracts/NewCoin.json'));
var provider = new web3.providers.HttpProvider("http://localhost:8545");
var MyContract = contract(MyContractJSON);
MyContract.setProvider(provider);
MyContract.deployed().then(function(instance){
return instance.returnfive();
})
.then(function(result) {
console.log(result);
}, function(error) {
console.log(error);
});
I set this code to call a smart contract function that returns 5.
I tested it with truffle console and it works properly.
But when trying to get the same result using nodejs it crashes giving those 2 errors :
(node:6227) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): TypeError: Cannot read property 'apply' of undefined
(node:6227) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Any idea about the issue ?

Replace MyContract definition with
const MyContract = artifacts.require("MyContractewCoin")
// You are missing this step before invoking deployer
await deployer.deploy(MyContract)
const dMyContract = await MyContract.deployed()
// now you can do stuff like
let result = await dMyContract.someContractFunction(args)

Related

Proactive Teams message - trustServiceUrl The "url" argument must be of type string

I'm trying to send a proactive teams message to an existing conversation using node.
Have installed bot for a user as per method described within https://learn.microsoft.com/en-us/microsoftteams/platform/graph-api/proactive-bots-and-messages/graph-proactive-bots-and-messages?tabs=javascript and also retrieved the conversation chatId.
My aim is to create a "console" style application where I can push a proactive message to this conversation, but am stuck with passing a valid URL through to the trustServiceUrl method and observe the following error:
TypeError [ERR_INVALID_ARG_TYPE]: The "url" argument must be of type string. Received type undefined
Sample code:
const path = require('path');
const botbuilder = require('botbuilder');
const ENV_FILE = path.join(__dirname, '.env');
require('dotenv').config({ path: ENV_FILE });
const { MicrosoftAppCredentials } = require('botframework-connector');
const adapter = new botbuilder.BotFrameworkAdapter({
appId: process.env.MicrosoftAppId,
appPassword: process.env.MicrosoftAppPassword
});
async function Main() {
var conversationRef = '[MY TEAMS CONVERSATION REFERENCE]';
let response = await sendMessage(conversationRef);
}
function sendMessage(conversationRef) {
var promise = new Promise(function(resolve, reject) {
adapter.continueConversation(conversationRef, async turnContext => {
const serviceUrl = 'https://smba.trafficmanager.net/uk/';
MicrosoftAppCredentials.trustServiceUrl(serviceUrl);
await turnContext.sendActivity('proactive hello');
});
});
return promise;
}
Main();
I know I'm overlooking something obvious, but am stuck with the above error - appreciate any steer.
Thanks!
Trace below:
(node:16504) UnhandledPromiseRejectionWarning: TypeError [ERR_INVALID_ARG_TYPE]: The "url" argument must be of type string. Received type undefined
at validateString (internal/validators.js:118:11)
at Url.parse (url.js:159:3)
at Object.urlParse [as parse] (url.js:154:13)
at Function.trustServiceUrl (C:\dev\demo\botFramework\node_modules\botframework-connector\lib\auth\appCredentials.js:68:25)
at BotFrameworkAdapter.<anonymous> (C:\dev\demo\botFramework\node_modules\botbuilder\lib\botFrameworkAdapter.js:153:57)
at Generator.next (<anonymous>)
at C:\dev\demo\botFramework\node_modules\botbuilder\lib\botFrameworkAdapter.js:14:71
at new Promise (<anonymous>)
at __awaiter (C:\dev\demo\botFramework\node_modules\botbuilder\lib\botFrameworkAdapter.js:10:12)
at BotFrameworkAdapter.continueConversation (C:\dev\demo\botFramework\node_modules\botbuilder\lib\botFrameworkAdapter.js:139:16)
(node:16504) 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(). (rejection id: 1)
(node:16504) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
PS C:\dev\demo\botFramework>
Please ensure that your conversationRef has a serviceUrl property. It's likely the same one that you set for trustServiceUrl()
See comments from #mdrichardson - my reference was not well formed and did not include all of the required properties.

Unzipper stream "Bad password" issue in node js

I am extracting password protected zip in node js for this i am using unzipper node module. below is the code which i am using.
const unzipper = require('unzipper');
const fs = require('fs');
const path = require('path');
async function checkPasswordValid(zipFilePath, password) {
let directory = null;
try {
directory = await unzipper.Open.file(zipFilePath);
return new Promise((resolve, reject) => {
// console.log(directory.files[0].path)
directory.files[0].stream(password)
.on('error', (err) => {
console.log('I am heere too bro in error')
console.log(err.message);
})
.on("readable", () => {
console.log('I am heere too bro')
})
});
}
catch (err) {
console.log('I am heere too bro in error in catch')
console.log(err.message);
}
}
let zpath = 'D:/NodeJs/upload/zip/text.zip';
let exPath = 'D:/NodeJs/upload/extractFile/';
let pass = 'DEXTER';
checkPasswordValid(zpath, pass)
when i try to manually open zip with password it's works fine but when i am using same password with node module unzipper i am getting below error.
I am heere too bro in error
BAD_PASSWORD
(node:6100) UnhandledPromiseRejectionWarning: #<Object>
(node:6100) 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(). (rejection id: 1)
(node:6100) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
I don't know where i am doing wrong. Code looks perfect for me but not working. to made password protected zip i used winrar software on windows 10.
It appears that unzipper doesn't support all encryption methods. This issue has produced a feature request that has not been developed yet.

Unit Testing HTTP Post request with database access

Hi I'm currently trying to learn and implement some unit testing for my HTTP Requests. currently I have a SQlite db setup, and a simple post request. This is the test I have written so far:
"use strict";
process.env.NODE_ENV = 'test';
const chai = require('chai');
const chaiHttp = require('chai-http');
chai.use(chaiHttp);
const expect = chai.expect;
const app = require('../../../app');
chai.request('http://localhost:8080')
.put('/tempValue')
.send({sensorid: '1', sensorValue: '25.00', timeRecorded: '2020-04-12 12:30'})
.then(function (res) {
expect(res).to.have.status(200);
})
.catch(function (err) {
throw err;
});
I seem to be getting a error that it is unable to open the database file. Currently I am just connecting to the database in the app.js file, using const dbPath = "./database/database.db"; and const dbConnection = sqlite.open(dbPath, { Promise });
I also seem to get errors about incorrect use of .catch? This is the error log:
(node:13952) UnhandledPromiseRejectionWarning: Error: SQLITE_CANTOPEN: unable to open database file
(node:13952) 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(). To terminate the node process on unha
ndled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:13952) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
(node:13952) UnhandledPromiseRejectionWarning: AssertionError: expected { Object (_events, _eventsCount, ...) } to have status code 200 but got 404
at D:\Uni Work\3rd Year\302CEM - Agile Development\Penguin Project\test\api\temperature\get.js:15:29
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:13952) 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(). To terminate the node process on unha
ndled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
Thanks for any help!
EDIT:
This is the particular post request I'm testing, it uses MQTT to check if the message being sent is to that topic structure, then inserts into the database.
app.ws.use(route.all('/tempValue', function (ctx){
client.on('message', async function(topic,message){
console.log(topic, message.toString());
if (topic === '302CEM/Penguin/Room1/Temperature'){
const SQL = "INSERT INTO sensorData (sensorid, sensorValue, timeRecorded) VALUES (?,?,?)";
try {
const temptostring = message.toString();
const db = await dbConnection;
await db.run(SQL, ["1",temptostring, moment().format('YYYY-MM-DD HH:mm')]);
ctx.websocket.send(temptostring);
} catch (err) {
console.log(err);
}
}
})
}));

(node:11254) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'length' of null

I'm trying to query my Firebase database on NodeJS, I have
var admin = require("firebase-admin");
var serviceAccount = require('/path/app-firebase-adminsdk-bs45c-5a33370488.json');
var firebase = admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://app.firebaseio.com/"
});
var fcmToken = "";
var ref = firebase.database().ref("users");
ref.once("value")
.then(function(snapshot) {
var data = snapshot.val();
console.log(data);
for(var i=0; i<data.length; i++){
if(phone == '9786733361'){
fcmToken = data[i].fcmToken
}
}
console.log(fcmToken);
});
I ran node database.js
and kept getting
(node:11254) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'length' of null
(node:11254) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
How would one go about and debug this further?
DataSnapshot's val() can be null, meaning that the object is empty.
Hence your call for data.length will fail since you're trying to call that on undefined / null.
At this point it's hard to make assumptions about the data stored online, but you should double check the event you're listening for in once is indeed there.

"The iterator does not provide a 'throw' method." in Foreach node.js

I'm having trouble with nodejs generators, when I launch my code I got the following error :
node:3632) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: The iterator does not provide a 'throw' method.
(node:3632) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
The code is the following , I use AdoniJs. User.all and user.typeModule are both database relations.
// This is the function that is called at the defined schedule
* handle () {
const usersWrapper = yield User.all()
yield * usersWrapper.map(function * (user) {
const typeModulesWrapper = yield user.typeModule()
typeModulesWrapper.map(function (module) {
const Controller = use(module.controller_path)
Controller.event()
})
})
}
}
Thank you

Resources