Unexpected token ')' Nodejs with Couchdb - node.js

I am using nodejs 14 and couchdb database 3.1.1
I am trying to connect and display list of couchdb databases using nodejs but following error occur
const NodeCouchDb = require('node-couchdb');`
const couch = new NodeCouchDb();
// node-couchdb instance with Memcached
const MemcacheNode = require('node-couchdb-plugin-memcached');
const couchWithMemcache = new NodeCouchDb({
cache: new MemcacheNode
});
// node-couchdb instance talking to external service
const couchExternal = new NodeCouchDb({
host: 'couchdb.external.service',
protocol: 'https',
port: 5984
});
// not admin party
const couchAuth = new NodeCouchDb({
auth: {
user: 'admin',
pass: 'godhelp'
}
});
couch.listDatabases()
.then(
dbs => dbs.map(...),
err => {
// request error occured
});
ERROR After Compiled :
dbs => dbs.map(...),
^
SyntaxError: Unexpected token ')'
at wrapSafe (internal/modules/cjs/loader.js:988:16)
at Module._compile (internal/modules/cjs/loader.js:1036:27)
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

I think there is a syntax error in your code, but more fundamentally node-couchdb seems to be an inactive library that has not been updated in more than four years. I would recommend using nano, which is the official Apache CouchDB NodeJS library.
Here's a simple NodeJS script (index.js) using nano to list your databases.
const nano = require('nano')(process.env.COUCH_URL)
const main = async function() {
const response = await nano.db.list()
console.log(response)
}
main ()
You will need to create an environment variable called COUCH_URL:
export COUCH_URL="http://user:password#localhost:5984"
and then run the script:
node index.js
#[ 'deeds' ]

Related

Unexpected token '.' while trying to use Nodemailer SES transport sdk

I need to extend the functionality of my SMTP feature to handle bulk emails. It works fine, however when a big amount of emails presented it sends them very slowly (about 2-3 per second). Our current AWS plan allows up to 15 emails per second. I read NodeMailer documentation and tried to implement the SES SDK, however it crashes my app right away.
Here is an error:
/home/node/app/node_modules/#aws-sdk/client-ses/dist-cjs/protocols/Aws_query.js:3734
if (input.ReplacementTags?.length === 0) {
^
SyntaxError: Unexpected token '.'
at wrapSafe (internal/modules/cjs/loader.js:915:16)
at Module._compile (internal/modules/cjs/loader.js:963:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
at Module.load (internal/modules/cjs/loader.js:863:32)
at Function.Module._load (internal/modules/cjs/loader.js:708:14)
at Module.require (internal/modules/cjs/loader.js:887:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Object.<anonymous> (/home/node/app/node_modules/#aws-sdk/client-ses/dist-cjs/commands/CloneReceiptRuleSetCommand.js:8:21)
at Module._compile (internal/modules/cjs/loader.js:999:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
[nodemon] app crashed - waiting for file changes before starting...
Here is my dependency list:
"#aws-sdk/client-ses": "^3.204.0",
"#aws-sdk/credential-provider-node": "^3.204.0",
"nodemailer": "^6.4.16"
And here is my nodeMailer code:
require('dotenv').config()
const nodemailer = require('nodemailer')
const Settings = require('./agentLogic/settings')
const Util = require('./util')
let aws = require('#aws-sdk/client-ses') // new feature I'm trying to implement
let {defaultProvider} = require('#aws-sdk/credential-provider-node') // new feature I'm trying to implement
const ses = new aws.SES({
apiVersion: '2010-12-01',
region: 'us-west-2',
defaultProvider,
}) // new feature I'm trying to implement
let currentSMTP = {}
async function emailService() {
currentSMTP = await Settings.getSMTP()
const decryptedPassword = Util.decrypt(
currentSMTP.dataValues.value.auth.pass,
currentSMTP.dataValues.value.IV,
)
const transporter = nodemailer.createTransport({
host: currentSMTP.dataValues.value.host,
// Defaults to 587 if "secure" is false or no value provided or 465 if true
port:
currentSMTP.dataValues.value.encryption === false
? 587
: !currentSMTP.dataValues.value.encryption
? 587
: currentSMTP.dataValues.value.encryption,
// False for STARTTLS (must use port 587), true for TLS (must use port 465)
secure: !currentSMTP.dataValues.value.encryption
? false
: currentSMTP.dataValues.value.encryption,
auth: {
user: currentSMTP.dataValues.value.auth.mailUsername
? currentSMTP.dataValues.value.auth.mailUsername
: currentSMTP.dataValues.value.auth.email,
pass: decryptedPassword,
},
tls: {
// Change to "false" to not fail on invalid certs
rejectUnauthorized: true,
},
SES: {ses, aws}, // new feature I'm trying to implement
sendingRate: 15, // new feature I'm trying to implement (I need this to match our current AWS SMTP plan of 15 emails/second)
})
return transporter
}
const sendMail = async (message) => {
const transporter = await emailService()
return new Promise((resolve, reject) => {
transporter.sendMail(message, (error, info) => {
if (error) {
console.log('Error occurred')
console.log(error.message)
reject('error')
} else {
console.log('Message sent successfully!')
console.log(nodemailer.getTestMessageUrl(info))
resolve(true)
}
// Only needed when using pooled connections
transporter.close()
})
})
}
Please, note that by default all the SMTP settings are not set. The user may or may not set the SMTP on demand. But the app comes without some SMTP preset values (such as host, username, email etc)
Can anyone help me understand why I'm getting and how to fix it?

My code is giving an error- Error [TOKEN_INVALID]: An invalid token was provided

I am trying to create a Discord Bot. I just added some basic code, and then tried to run it.
Basically, I am trying to create a Discord Bot for my server. I learned a bit of a JavaScript and decided to give it a try.
I tried searching for similar problems on the internet, but nothing worked.
Command Prompt
Copyright (C) Microsoft Corporation. All rights reserved.
Install the latest PowerShell for new features and improvements! https://aka.ms/PSWindows
PS C:\Users\RadoN\Desktop\Desktop items\RadoN's folder\Coding\a! RL Utilities - V2> npm run test
> rl-utilitiesv2#1.0.0 test
> node src/bot.js
C:\Users\RadoN\Desktop\Desktop items\RadoN's folder\Coding\a! RL Utilities - V2\node_modules\discord.js\src\client\Client.js:237
if (!token || typeof token !== 'string') throw new Error('TOKEN_INVALID');
^
Error [TOKEN_INVALID]: An invalid token was provided.
at Client.login (C:\Users\RadoN\Desktop\Desktop items\RadoN's folder\Coding\a! RL Utilities - V2\node_modules\discord.js\src\client\Client.js:237:52)
at Object.<anonymous> (C:\Users\RadoN\Desktop\Desktop items\RadoN's folder\Coding\a! RL Utilities - V2\src\bot.js:16:8)
at Module._compile (node:internal/modules/cjs/loader:1097:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1149:10)
at Module.load (node:internal/modules/cjs/loader:975:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
at node:internal/main/run_main_module:17:47 {
[Symbol(code)]: 'TOKEN_INVALID'
}
Node.js v17.4.0
bot.js
const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS] })
require('dotenv').config();
client.on('ready', () => {
// console.log(`Bot ready for work. Logged in as ${client.user.tag}!`)
console.log(process.env.token)
});
(async () => {
client.login(process.env.token);
})();

How do I Fix a Cannot find module '.functions/handleCommands.js' error?

Upon running my Bot to have it sign-on after installing a command and event handler I got the error
Error: Cannot find module '.functions/handleCommands.js'
Require stack:
C:\Users\levan\Desktop\Discordbot\Bot Templates\2 command handling\src\bot.js
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
at Function.Module._load (node:internal/modules/cjs/loader:778:27)
at Module.require (node:internal/modules/cjs/loader:999:19)
at require (node:internal/modules/cjs/helpers:102:18)
at C:\Users\levan\Desktop\Discordbot\Bot Templates\2 command handling\src\bot.js:14:9
at Object.<anonymous> (C:\Users\levan\Desktop\Discordbot\Bot Templates\2 command handling\src\bot.js:19:3)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1147:10)
at Module.load (node:internal/modules/cjs/loader:975:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12) { code:
'MODULE_NOT_FOUND',
requireStack: [
'C:\\Users\\levan\\Desktop\\Discordbot\\Bot Templates\\2 command handling\\src\\bot.js'
After looking thru the folder functions and the handleCommands.js, I Still cannot figure out what I'm missing or what I might on messed up. I thought that maybe my module.exports was in the wrong place but moving things around did not solve the issue either.
const { Routes } = require('discord-api-types/v9');
const fs = require('fs');
const clientId = 'redacted'; // your bots token
const guildId = 'redacted'; // the server id the bot will be on
module.exports = (clinet) => {
clinet.handleCommands = async (commandFolders, path) =>{
clinet.commandArray = [];
for(folder of commandFolders){
const commandFiles = fs.readdirSync(`${path}/${folder}`).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`../commands/${folder}/${file}`);
// Set a new item in the Collection
// With the key as the command name and the value as the exported module
client.commands.set(command.data.name, command);
clinet.commandArray.push(command.data.toJSON());
}
}
};
};
const rest = new REST({ version: '9' }).setToken(process.env.token);
(async () => {
try {
console.log('Started refreshing application (/) commands.');
await rest.put(
Routes.applicationGuildCommands(clientId, guildId),
{ body: clinet.commandArray },
);
console.log('Successfully reloaded application (/) commands.');
} catch (error) {
console.error(error);
}
})();
As the error was MODULE_NOT_FOUND I figured that maybe I didn't run all the installs I need to make my bot work. After running thru my npm lists the error persisted.
NPM's Installed
"npm init"
"npm install discord.js"
"npm install dotenv"
"npm install discord.js dotenv"
"npm install #discordjs/rest discord-api-types #discordjs/builders"
My goal is to be the Bot back online and to figure out how to troubleshoot this sort of error in case it comes up again. Any help you can give will be greatly appreciated.
'.functions/handleCommands.js' should have been './functions/handleCommands.js' Caffeine is not a substitute for sleep

No AuthProvider for DEFAULT defined with mongoose 6

When updating to Mongoose 6 with Mongodb nodejs driver version 4, I have the error below:
MongoInvalidArgumentError: No AuthProvider for DEFAULT defined.
at prepareHandshakeDocument (/home/arch/git/project/node_modules/mongodb/lib/cmap/connect.js:153:29)
at performInitialHandshake (/home/arch/git/project/node_modules/mongodb/lib/cmap/connect.js:63:5)
at /home/arch/git/project/node_modules/mongodb/lib/cmap/connect.js:25:9
at callback (/home/arch/git/project/node_modules/mongodb/lib/cmap/connect.js:244:9)
at Socket.connectHandler (/home/arch/git/project/node_modules/mongodb/lib/cmap/connect.js:282:9)
at Object.onceWrapper (events.js:519:28)
at Socket.emit (events.js:400:28)
at Socket.emit (domain.js:470:12)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1134:10)
From previous event:
at NativeConnection.Connection.openUri (/home/arch/git/project/node_modules/mongoose/lib/connection.js:778:19)
at /home/arch/git/project/node_modules/mongoose/lib/index.js:330:10
at promiseOrCallback (/home/arch/git/project/node_modules/mongoose/lib/helpers/promiseOrCallback.js:10:12)
at Mongoose._promiseOrCallback (/home/arch/git/project/node_modules/mongoose/lib/index.js:1151:10)
at Mongoose.connect (/home/arch/git/project/node_modules/mongoose/lib/index.js:329:20)
at connectToDb (/home/arch/git/project/core/configs/database.js:101:8)
at createServer (/home/arch/git/project/app.js:65:16)
at Object.<anonymous> (/home/arch/git/project/app.js:262:3)
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
I don't have any authentication set up (this is my local development environment) so I don't understand where is the issue comming from. Here is the relevant connection code:
let connectionURL = 'mongodb://';
const connectionOptions = {
authSource: options.authSource,
};
if (options.user && options.password) {
connectionURL += `${options.user}:${options.password}#`;
}
connectionURL += `${options.host}/${dbName}?authSource=${options.authSource}`;
mongoose
.connect(connectionURL, connectionOptions, function onConnected(err) {
if (err) {
return cb(new Error(`Can not connect to database ${dbName}`));
}
return cb(null, mongoose.connection);
});
For a passwordless/userless connection, making sure the connection url doesn't contain authSource worked for me. This worked somehow before the version 4 of the driver, but not any more.
Also, either choose wether to pass options in the object or in the connection string. As the doc says:
Best practice is to put options that likely differ between development and production, like replicaSet or ssl, in the connection string, and options that should remain constant, like connectTimeoutMS or poolSize, in the options object
const connectionOptions = {};
if (options.user && options.password) {
connectionOptions.user = options.user;
connectionOptions.password = options.password;
connectionOptions.authSource = options.authSource;
}
const connectionURL = `mongodb://${options.host}/${dbName}`;
mongoose
.connect(connectionURL, connectionOptions, function onConnected(err) {
if (err) {
return cb(new Error(`Can not connect to database ${dbName}`));
}
return cb(null, mongoose.connection);
});
};

Node.js, Express.js - unexpected token {

My app crashes every time it reaches this line:
const {name, price} = req.query;
^
can't seem to locate the exact answer..here is the error log
SyntaxError: Unexpected token {
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 Function.Module.runMain (module.js:441:10)
at startup (node.js:140:18)
at node.js:1043:3
context:
app.get('/products/add' , (req, res) => {
const {name, price} = req.query;
const INSERT_PRODUCTS_QUERY = `INSERT INTO products (name, price) VALUES ('${ name }', ${ price })`;
connection.query(INSERT_PRODUCTS_QUERY, (err,results) => {
if(err)
{
return res.send(err);
}
else
{
return res.send('succesfully added product');
}
});
});
According to node.green, the object destructuring with primitives syntax works after Node.JS v6.4.0, and throws the Unexpected Token { on Node.js versions below that.
Also, the object rest/spread properties only works out of the box from Node v8.6.0. It works in v8.2.1 with the --harmony flag, and throws the Unexpected Token ... on Node.js versions below that.
You tried to use destructuring assignment. AFAIK its support by nodejs v.6+ from a box and from 4.2.2 with flag --harmony_destructuring

Resources