NodeJs await is only valid in async function [duplicate] - node.js

This question already has answers here:
await is only valid in async function
(14 answers)
How to resolve the Syntax error : await is only valid in async function?
(2 answers)
Closed 2 years ago.
I am trying to set some data in firestore using this node js code :
const db = admin.firestore();
const allDB = db.collection("like").doc("all").collection("movies");
const s1 = db.collection("like").doc("all");
await s1.set({
type: ["all"],
});
running the file in console : node file.js
Gives me this error :
await s1.set({
^^^^^
SyntaxError: await is only valid in async function
at wrapSafe (internal/modules/cjs/loader.js:1053:16)
at Module._compile (internal/modules/cjs/loader.js:1101:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
at Module.load (internal/modules/cjs/loader.js:985:32)
at Function.Module._load (internal/modules/cjs/loader.js:878:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
at internal/main/run_main_module.js:17:47
How to solve this issue

Wrap your code in async function
async function run(){
const db = admin.firestore();
const allDB = db.collection("like").doc("all").collection("movies");
const s1 = db.collection("like").doc("all");
await s1.set({
type: ["all"],
});
}
run().catch(e => { console.error(e); process.exit(-1); })

You should use it inside an async function, this will work:
const doSomething = async () => {
const db = admin.firestore();
const allDB = db.collection("like").doc("all").collection("movies");
const s1 = db.collection("like").doc("all");
await s1.set({
type: ["all"],
});
}

like in the answer above, you just need to make an async function by using the async title thing, then naming a function with the stuff inside it

Related

My discord js command handler not working

Hey i can't seem to get my command handler to work with multiple command file could someone help me with this i tried multiple ways i can't seem to get it to work with multiple folders. I'm a bit new to Discord js as well i had one working then i wanted to make it more organized and i can't seem to get it to work
const fs = require(`fs`);
module.exports = (client, Discord) => {
const command_files = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
const command_files = fs.readdirSync('./moderationcommands/').filter(file => file.endsWith('.js'));
for (const file of command_files) {
const command = require(`../commands/${file}`, `../moderationcommands/${file}`);
if (command.name) {
client.commands.set(command.name, command);
} else {
continue;
}
}
}
Here's the error
PS C:\Users\lolzy\OneDrive\Desktop\discordbot> node .
C:\Users\lolzy\OneDrive\Desktop\discordbot\handlers\command_handler.js:5
const command_files = fs.readdirSync('./moderationcommands/').filter(file => file.endsWith('.js'));
^
SyntaxError: Identifier 'command_files' has already been declared
at wrapSafe (internal/modules/cjs/loader.js:984:16)
at Module._compile (internal/modules/cjs/loader.js:1032:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1097:10)
at Module.load (internal/modules/cjs/loader.js:933:32)
at Function.Module._load (internal/modules/cjs/loader.js:774:14)
at Module.require (internal/modules/cjs/loader.js:957:19)
at require (internal/modules/cjs/helpers.js:88:18)
at C:\Users\lolzy\OneDrive\Desktop\discordbot\main.js:13:5
at Array.forEach (<anonymous>)
at Object.<anonymous> (C:\Users\lolzy\OneDrive\Desktop\discordbot\main.js:12:38)
PS C:\Users\lolzy\OneDrive\Desktop\discordbot>
You named two variables exactly the same:
const command_files = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
const command_files = fs.readdirSync('./moderationcommands/').filter(file => file.endsWith('.js'));
You just have to make sure, that they have different names

While I was trying to connect Mondo DB, event.bind stopped working as a function

I've got all the packages necessary and whatnot but I keep on getting an error. First of all, here's my coding (in a file called main.js.):
const client = new Discord.Client();
require("dotenv").config();
const fs = require('fs');
const mongoose = require('mongoose');
client.commands = new Discord.Collection();
client.events = new Discord.Collection();
["command_handler", "event_handler"].forEach((handler) => {
require(`./handlers/${handler}`)(client, Discord);
});
mongoose
.connect(process.env.MONGODB_SRV, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
})
.then(()=>{
console.log('Connected to the database!');
})
.catch((err) => {
console.log(err);
});
client.login(process.env.DISCORD_TOKEN);
My error is
C:\Users\shann\Desktop\DiscordBot\handlers\event_handler.js:10
client.on(event_name, event.bind(null, Discord, client));
^
TypeError: event.bind is not a function
at load_dir (C:\Users\shann\Desktop\DiscordBot\handlers\event_handler.js:10:41)
at C:\Users\shann\Desktop\DiscordBot\handlers\event_handler.js:14:38
at Array.forEach (<anonymous>)
at module.exports (C:\Users\shann\Desktop\DiscordBot\handlers\event_handler.js:14:25)
at C:\Users\shann\Desktop\DiscordBot\main.js:11:37
at Array.forEach (<anonymous>)
at Object.<anonymous> (C:\Users\shann\Desktop\DiscordBot\main.js:10:38)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
at internal/main/run_main_module.js:17:47
I honestly don't know what the problem is this time. Should I define event.bind? I thought .bind was a function and event was the variable. I've been following a tutorial. I do have mongoose installed through the command center but I don't know if I should reinstall it. Also, I don't see any errors in my coding but I am pretty new so please point them out and how I can fix it!
The coding for command_handler.js
const fs = require('fs');
module.exports = (client, Discord)=>{
const command_files = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
for(const file of command_files){
const command = require(`../commands/${file}`)
if(command.name){
client.commands.set(command.name, command);
} else {
continue;
}
}
}
The coding for event_handler.js is
const fs = require('fs');
module.exports = (client, Discord)=>{
const load_dir = (dirs)=>{
const event_files = fs.readdirSync(`./events/${dirs}`).filter(file => file.endsWith('.js'));
for(const file of event_files){
const event = require(`../events/${dirs}/${file}`);
const event_name = file.split('.')[0];
client.on(event_name, event.bind(null, Discord, client));
}
}
['client', 'guild'].forEach(e => load_dir(e));
}
There isn't actually much of an answer here but the thing is, you don't even need an advanced event handler. All I did was remove the event handler from my handlers and added an event handler to my main.js. Then I removed client and guild from my events. After that, I made it so that in main.js it would look at all the files in events (the folder with all my events) and run them (using fs)!
Credits to #WorthyAlpaca for the help in introducing this alternate method

TypeError: notesExist.push is not a function?

i'm just newbie on nodeJs ,and i need your help
my utile.js file :
const fs = require('fs');
const addNotes = function(name,age,birthday){
const notesExist = loadNotes()
notesExist.push({
name: name,
age: age,
birthday:birthday
})
}
const loadNotes = function (){
try{
binaryVersion = fs.readFileSync('./JsonFile/data.json');
stringVersion = binaryVersion.toString();
dataParsed = JSON.parse(stringVersion);
return dataParsed;
}
catch(err){
return [];
}
}
module.exports = {
addNotes: addNotes,
loadNotes: loadNotes
}
my intro.js file
yargs = require('yargs');
const utile = require('./utile.js');
yargs.command({
command: 'add',
describe: 'Adding new record',
builder:{
name:{
describe:'note name',
demandOption:true, // title option to be requires in the command line
type:'string' //requie a string as title value
},
age:{
describe:'note age',
demandOption:true,
type:'string' //require astring as body value
},
birthday:{
describe:'note birthday',
demandOption:true,
type:'string' //require astring as body value
},
},
handler: function(argv){
// console.log(chalk.green(chalk.red(argv.title)))
/* console.log(chalk.green(chalk.green(argv.body))) */
utile.addNotes(argv.name,argv.age,argv.birthday);
}
});
my data.json file :
{"name":"Hannani","age":25,"birthday":1995}
But when i run the intro.js file by : node intro.js add --name="booktitle" --age="dsds" --birthday="1995" i got i nice erro [I spent 3 hours but i didn't find anything to solve that error ]
Error :
/home/simo/Documents/nodeJs/node_modules/yargs/yargs.js:1195
else throw err
^
TypeError: notesExist.push is not a function
at Object.addNotes (/home/simo/Documents/nodeJs/utile.js:34:20)
at Object.handler (/home/simo/Documents/nodeJs/intro.js:56:19)
at Object.runCommand (/home/simo/Documents/nodeJs/node_modules/yargs/lib/command.js:240:40)
at Object.parseArgs [as _parseArgs] (/home/simo/Documents/nodeJs/node_modules/yargs/yargs.js:1107:41)
at Object.parse (/home/simo/Documents/nodeJs/node_modules/yargs/yargs.js:566:25)
at Object.<anonymous> (/home/simo/Documents/nodeJs/intro.js:86:7)
at Module._compile (internal/modules/cjs/loader.js:1151:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1171:10)
at Module.load (internal/modules/cjs/loader.js:1000:32)
at Function.Module._load (internal/modules/cjs/loader.js:899:14)
ps: I didn't change anything in my yargs.js file ..
Please what i'm doing wrong ? Thanks in advance !
THe data.json needs to be array format for you to be able to push. Something like this
[{"name":"Hannani","age":25,"birthday":1995}]
Also, since it is a normal json file you could simply require it as will instead of using fs to read it.
const data = require('./JsonFile/data.json')
Hope this helps.

How to add an exception or manage the error at the following node function?

Here is my original code:
function extract_number(conv){
const regex = /(?:(\+?\d{1,3}) )?(?:([\(]?\d+[\)]?)[ -])?(\d{1,5}[\- ]?\d{1,5})/
const result = conv.match(regex)
const value = result[0]
console.log(value);
return value
}
However it is falling with the string does not contains a number to extract
here the example:
extract_number('my number is')
I tried to catch the error as follows:
function extract_number(err,conv){
if (err) {
const regex = /(?:(\+?\d{1,3}) )?(?:([\(]?\d+[\)]?)[ -])?(\d{1,5}[\- ]?\d{1,5})/
const result = conv.match(regex)
const value = result[0]
console.error('There was an error', err);
}
console.log(value)
return value
}
I got:
/home/adolfo/node_js/index.js:61
const result = conv.match(regex)
^
TypeError: Cannot read property 'match' of undefined
at extract_number (/home/adolfo/node_js/index.js:61:29)
at Object.<anonymous> (/home/adolfo/node_js/index.js:69:1)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Function.Module.runMain (module.js:693:10)
at startup (bootstrap_node.js:188:16)
at bootstrap_node.js:609:3
at the seccond function, so I would like to appeciate support with this
Try..catch is your friend
function extract_number(conv){
try{
const regex = /(?:(\+?\d{1,3}) )?(?:([\(]?\d+[\)]?)[ -])?(\d{1,5}[\- ]?\d{1,5})/
const result = conv.match(regex)
const value = result[0]
console.log(value);
return value
}catch(){
return null
}
}
There's different approaches. You can do several checks on result on it's length or if it is type Array, and/or if conv is null or undefined and have that throw your error. Or you can implement a try/catch as specified here, which is probably the easiest way to accomplish what you're trying to do.
function extract_number(conv){
const regex = /(?:(\+?\d{1,3}) )?(?:([\(]?\d+[\)]?)[ -])?(\d{1,5}[\- ]?\d{1,5})/
let value;
try {
const result = conv.match(regex)
value = result[0]
} catch (err) {
console.error('There was an error', err);
}
console.log(value);
return value
}

use node-redis with node 8 util.promisify

node -v : 8.1.2
I use redis client node_redis with node 8 util.promisify , no blurbird.
the callback redis.get is ok, but promisify type get error message
TypeError: Cannot read property 'internal_send_command' of undefined
at get (D:\Github\redis-test\node_modules\redis\lib\commands.js:62:24)
at get (internal/util.js:229:26)
at D:\Github\redis-test\app.js:23:27
at Object. (D:\Github\redis-test\app.js:31:3)
at Module._compile (module.js:569:30)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:503:32)
at tryModuleLoad (module.js:466:12)
at Function.Module._load (module.js:458:3)
at Function.Module.runMain (module.js:605:10)
my test code
const util = require('util');
var redis = require("redis"),
client = redis.createClient({
host: "192.168.99.100",
port: 32768,
});
let get = util.promisify(client.get);
(async function () {
client.set(["aaa", JSON.stringify({
A: 'a',
B: 'b',
C: "C"
})]);
client.get("aaa", (err, value) => {
console.log(`use callback: ${value}`);
});
try {
let value = await get("aaa");
console.log(`use promisify: ${value}`);
} catch (e) {
console.log(`promisify error:`);
console.log(e);
}
client.quit();
})()
changing let get = util.promisify(client.get);
to let get = util.promisify(client.get).bind(client);
solved it for me :)
If you are using node v8 or higher, you can promisify node_redis with
util.promisify as in:
const {promisify} = require('util');
const getAsync = promisify(client.get).bind(client); // now getAsync is a promisified version of client.get:
// We expect a value 'foo': 'bar' to be present
// So instead of writing client.get('foo', cb); you have to write:
return getAsync('foo').then(function(res) {
console.log(res); // => 'bar'
});
or using async await:
async myFunc() {
const res = await getAsync('foo');
console.log(res);
}
culled shamelessly from redis official repo
You can also use Blue Bird Library plus monkey patching will do the trick for you.
For example:
const bluebird = require('bluebird')
const redis = require('redis')
async connectToRedis() {
// use your url to connect to redis
const url = '//localhost:6379'
const client = await redis.createClient({
url: this.url
})
client.get = bluebird.promisify(client.get).bind(client);
return client
}
// To connect to redis server and getting the key from redis
connectToRedis().then(client => client.get(/* Your Key */)).then(console.log)

Resources