AWS Lambda exports class not working - javascript

I am using NodeJs 6.10.2. I am using 2 files
index.js
var operation = require('./Handler/opHandler').opHandler;
var lambdaHandler = function () {
var o = new operation();
o.deleteMessage();
}
exports.lambdaHandler = function(event, context, callback) {
handleSQSMessages(context, callback);
};
opHandler.js
opHandler = function() {
this.db = '';
}
opHandler.prototype.deleteMessage = function (receiptHandle, callback) {
// My code here
// this.db = 'new val';
}
exports.opHandler = opHandler;
when run index.lambdaHandler on AWS Lambda with NodeJs 6.10, following error occurs
Syntax error in module 'index': SyntaxError
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:373:25)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (/var/task/index.js:16:13)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
I have googled and found similar issue here but according to it above code should work in NodeJs 6.10

Try another method or module export. It should work in your case.
index.js
var operation = require('./Handler/opHandler');
var lambdaHandler = function () {
var o = new operation();
o.deleteMessage();
}
exports.lambdaHandler = function(event, context, callback) {
handleSQSMessages(context, callback);
};
opHandler.js
opHandler = function() {
this.db = '';
}
opHandler.prototype.deleteMessage = function (receiptHandle, callback) {
// My code here
// this.db = 'new val';
}
module.exports = opHandler;
It solved my issue may help you out.

Related

Unexpected identifier in Discord.js

I'm coding a Discord bot in Discord.js v13, and this is my slash command handler:
const { Client } = require("discord.js");
const { promisify } = require("util");
const { glob } = require("glob");
const PG = promisify(glob);
const Ascii = require("ascii-table");
/**
* #param { Client } client
*/
module.exports = async(client => {
const Table = new Ascii("Commands loaded");
CommandsArray = [];
(await PG(`${process.cwd()}/Commands/*/*.js`)).map(async (file) => {
const command = require(file);
client.commands.set(command.name, command);
CommandsArray.push(command);
await Table.addRow(command.name, "🟢 SUCCESSFUL");
});
console.log(Table.toString());
});
However when I run it, I get this error (line 15):
(await PG(`${process.cwd()}/Commands/*/*.js`)).map(async (file) => {
^^
SyntaxError: Unexpected identifier
at Object.compileFunction (node:vm:352:18)
at wrapSafe (node:internal/modules/cjs/loader:1032:15)
at Module._compile (node:internal/modules/cjs/loader:1067:27)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1155:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Object.<anonymous> (C:\Users\Gabriel-User\Desktop\Discord Bots\adventurecraft-bot\index.js:7:1)
at Module._compile (node:internal/modules/cjs/loader:1103:14)
Any ideas on what I could do to improve my code?
When you are trying to await PG, it has no where to go so you have to assign it to a variable and then use that later on to get your desired outcome.
const someVariable = await PG(`${process.cwd()}/Commands/*/*.js`).map(async (file) => {
const command = require(file);
client.commands.set(command.name, command);
CommandsArray.push(command);
await Table.addRow(command.name, "🟢 SUCCESSFUL");
});

Discord.js & Canvacord: Error: libuuid.so.1: cannot open shared object file: No such file or directory

After I added level.js file in my commands folder and ran the bot, it showed up the error:
node:internal/modules/cjs/loader:1183
return process.dlopen(module, path.toNamespacedPath(filename));
^
Error: libuuid.so.1: cannot open shared object file: No such file or directory
at Object.Module._extensions..node (node:internal/modules/cjs/loader:1183:18)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:94:18)
at Object.<anonymous> (/home/runner/UnfortunateDistortedEngine/node_modules/canvas/lib/bindings.js:3:18)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:94:18)
at Object.<anonymous> (/home/runner/UnfortunateDistortedEngine/node_modules/canvas/lib/canvas.js:9:18)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10) {
code: 'ERR_DLOPEN_FAILED'
}
The code of level.js file:
const { client, CommandInteraction, MessageEmbed } = require("discord.js");
const db = require('quick.db')
const canvacord = require("canvacord");
const Levels = require('discord-xp')
module.exports = {
name: "level",
description: "Displays the user's level and XP.",
type: 'CHAT_INPUT',
options: [
{
name: "member",
type: "USER",
description: "Specify a user.",
required: false
}
],
run: async (client, interaction, args) => {
let user1 = message.author;
const Blacklisted = db.fetch(`blacklistedUsers_${user1.id}`)
if (Blacklisted === true) return;
let target = await interaction.options.getUser('member')
let mentionedMember = target || interaction.user;
const user = await Levels.fetch(mentionedMember.id, interaction.guild.id, true)
const rank = new canvacord.Rank()
.setAvatar(mentionedMember.displayAvatarURL({ format: 'png', size: 512 }))
.setCurrentXP(mentionedMember.xp || 0)
.setRequiredXP(Levels.xpFor(user.level + 1) || Levels.xpFor(1))
.setRank(user.position)
.setLevel(user.level)
.setStatus(mentionedMember.presence.status)
.setBackground("IMAGE", "https://i.pinimg.com/originals/22/90/0f/22900f16a05211e2562828b6b3fe86b7.jpg")
.setProgressBar("#FFFFFF")
.setUsername(mentionedMember.username)
.setDiscriminator(mentionedMember.discriminator);
rank.build()
.then(data => {
const attachment = new MessageAttachment(data, "RankCard.png");
interaction.followUp({
files: [attachment]
})
});
}
}
There already was an issue opened on GitHub, but the opener didn't state any solution, just said "Solved". This is related to the Canvacord package that uses canvas.
You need libuuid which is a dependency of node-canvas which in return is a dev dependency of canvacord, it is usually preinstalled in many linux systems although you can use
apt-get install libuuid1
to install it, this should solve the issue, please note that you might have to use Nix if you are using a host such as repl.it in which you do not have root access.
Well, if you're using replit it's showing that error... So, I suggest you to change your replit.nix with the given nix below it would definitely fixed your issue!
{ pkgs }: {
deps = [
pkgs.nodejs-16_x
pkgs.libuuid
];
env = {
LD_LIBRARY_PATH = pkgs.lib.makeLibraryPath [pkgs.libuuid];
};
}

No such file directory when compile solidity with node fs library

I'm trying to compile solidity using node compile.js. I have attached the code below:
Here is my simple demo structure:
contracts
node_modules
compile.js
Incrementer.sol
package.json
package-lock.json
Here is compile.js
const fs = require('fs');
const solc = require('solc');
const path = require('path');
// Get Path and Load Contract
const inboxPath = path.resolve(__dirname, 'Incrementer.sol');
console.log(inboxPath) // This one provide directory to read (/Users/amstriker/Desktop/Sdax/OnePlace/contracts/Incrementer.sol'
const source = fs.readFileSync(inboxPath, 'utf8'); // still getting stuck on this
// Compile Contract
const input = {
language: 'Solidity',
sources: {
'Incrementer.sol': {
content: source,
},
},
settings: {
outputSelection: {
'*': {
'*': ['*'],
},
},
},
};
const tempFile = JSON.parse(solc.compile(JSON.stringify(input)));
const contractFile = tempFile.contracts['Incrementer.sol']['Incrementer'];
// Export Contract Data
module.exports = contractFile;
Incrementer.sol:
pragma solidity ^0.8.0;
contract Incrementer {
uint256 public number;
constructor(uint256 _initialNumber) {
number = _initialNumber;
}
function increment(uint256 _value) public {
number = number + _value;
}
function reset() public {
number = 0;
}
}
Packages.json
{
"dependencies": {
"solc": "^0.8.0",
"web3": "^1.5.3"
}
}
I have been tried many different approach but still getting errors:
internal/fs/utils.js:314
throw err;
^
Error: ENOENT: no such file or directory, open
'/Users/amstriker/Desktop/Sdax/OnePlace/contracts/Incrementer.sol'
at Object.openSync (fs.js:498:3)
at Object.readFileSync (fs.js:394:35)
at Object.<anonymous> (/Users/amstriker/Desktop/Sdax/OnePlace/contracts/compile.js:7:19)
at Module._compile (internal/modules/cjs/loader.js:1072:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)
at Module.load (internal/modules/cjs/loader.js:937:32)
at Function.Module._load (internal/modules/cjs/loader.js:778:12)
at Module.require (internal/modules/cjs/loader.js:961:19)
at require (internal/modules/cjs/helpers.js:92:18)
at Object.<anonymous> (/Users/steven/Desktop/Sdax/OnePlace/contracts/get.js:2:17)
at Module._compile (internal/modules/cjs/loader.js:1072:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)
at Module.load (internal/modules/cjs/loader.js:937:32)
at Function.Module._load (internal/modules/cjs/loader.js:778:12)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
at internal/main/run_main_module.js:17:47 {
errno: -2,
syscall: 'open',
code: 'ENOENT',
path: '/Users/amstriker/Desktop/Sdax/OnePlace/contracts/Incrementer.sol'
}
Any helps would be appreciated!!.
It failed because of space solidity filename( Incrementer.sol). It is working fine after i changed from Incrementer.sol to Incrementer.sol.

TypeError('Router.use() requires a middleware function but got a ' + gettype(fn)) FeathersJS

Im trying to bind a method to my /userAuthenticationInfo route, I have made some changes in my code around some of the other posts on this issue but I can't get anything to work.
Im using feathersJS's implementation of express but even using express i still get the same error. Any help would be appreciated.
app.js
const feathers = require('#feathersjs/feathers');
const express = require('#feathersjs/express');
const nano = require('cloudant-nano');
const AnnotatorService = require('./services/api/AnnotatorService');
const app = express(feathers())
.configure(express.rest())
.use(express.json())
.use(express.urlencoded({ extended: true }));
app.use('/userAuthenticationInfo', AnnotatorService.getUserAuthenticationInfo('bobby', app));
AnnotatorService.js
const nano = require('cloudant-nano');
const couchdbservice = require('#kapmug/feathers-nano/lib/index');
const host = process.env.DB_HOST || '127.0.0.1:5984';
const auth = `${process.env.DB_USERNAME || 'admin'}:${process.env.DB_PASSWORD || 'welcome'}`;
const opts = {
url: `http://${auth}#${host}`,
};
const options = {
name: 'users',
connection: nano(opts),
database: 'users',
paginate: {
default: 5,
max: 200,
},
};
var params = {
limit: 5,
skip: 0,
};
module.exports.getUserAuthenticationInfo = function (username, app) {
console.log('mission accomplished');
};
Error log
/Users/dromero/Documents/annotator-backend/node_modules/express/lib/router/index.js:458
throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))
^
TypeError: Router.use() requires a middleware function but got a undefined
at Function.use (/Users/dromero/Documents/annotator-backend/node_modules/express/lib/router/index.js:458:13)
at Function.<anonymous> (/Users/dromero/Documents/annotator-backend/node_modules/express/lib/application.js:220:21)
at Array.forEach (<anonymous>)
at Function.use [as _super] (/Users/dromero/Documents/annotator-backend/node_modules/express/lib/application.js:217:7)
at Function.use (/Users/dromero/Documents/annotator-backend/node_modules/#feathersjs/express/lib/index.js:50:28)
at Function.newMethod [as use] (/Users/dromero/Documents/annotator-backend/node_modules/#feathersjs/express/node_modules/uberproto/lib/proto.js:34:20)
at Object.<anonymous> (/Users/dromero/Documents/annotator-backend/src/app.js:11:5)
at Module._compile (internal/modules/cjs/loader.js:776:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:829:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
In the app.use function you need to put a middleware function(pointer), whose declaration is like:
function(req, res, next){ ... }
But, by putting AnnotatorService.getUserAuthenticationInfo('bobby', app) you are actually Calling the function, which returns nothing, thus undefined.
So, it should be,
module.exports.getUserAuthenticationInfo = function (username, app) {
return function(req, res, next){
console.log('mission accomplished');
next()//or res.end() or res.send() whatever
}
};

TypeError: Cannot read property 'prototype' of undefined

I have an issue that I can't seem to resolve, mostly because I have little knowledge of why it is occurring in this particular scenario.
Here's the error :
TypeError: Cannot read property 'followers' of undefined
at Object.<anonymous> (C:\Users\username\Documents\My Lib\bot\src\bot.js:15:4)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:393:7)
at startup (bootstrap_node.js:150:9)
at bootstrap_node.js:508:3
and here's what the code looks like :
const Twit = require('twit'),
config = require('./config'),
init = new Twit(config);
function Twitter(twitter) {
this.twitter = twitter
}
Twitter.prototype.followers = function(params) {
this.twitter.get('followers/list', params, (err, data) => {
if (!err)
data.users.forEach(user => console.log(data))
})
};
var bot = Twitter(init);
bot.followers({ screen_name: 'myscreenname'})
Haha. I'm almost certain it's a silly mistake. I just can't seem to find the source.
Any help is and will be appreciated.
You forgot the new keyword. Try this:
var bot = new Twitter(init);

Categories