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
Related
My current code looks like this:
const gzip2 = zlib.createUnzip();
const pack2 = new tar.Unpack();
const source2 = Readable.from('public/img.tar.gz');
const destination2 = fs.createWriteStream('public/images2');
pipeline(source2, gzip2, pack2, destination2, (err) => {
if (err) {
console.error('An error occurred:', err);
process.exitCode = 1;
}
});
But I'm getting this error:
internal/streams/pipeline.js:108
throw new ERR_INVALID_ARG_TYPE(
^
TypeError [ERR_INVALID_ARG_TYPE]: The "val" argument must be an instance of Readable, Iterable, or AsyncIterable. Received an instance of Unpack
at makeAsyncIterable (internal/streams/pipeline.js:108:9)
at pipeline (internal/streams/pipeline.js:265:15)
at Object.<anonymous> (/mnt/c/index.js:39:1)
at Module._compile (internal/modules/cjs/loader.js:1068:30)
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 Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
at internal/main/run_main_module.js:17:47 {
code: 'ERR_INVALID_ARG_TYPE'
}
I've also tried
const pack2 = tar.extract();
without luck.
If anyone can help me to extract this tar file using pipeline, so that I can also unzip the file. I would be very grateful. I've seen people use .pipe(tar.extract()) online, but I'm trying to keep my code as clean and uniform as possible. This: https://www.npmjs.com/package/tar has unfortunately not been very helpful.
const tar = require('tar.gz2')
var read = tar().createReadStream('/public/images');
var write = fs.createWriteStream('compressed.tar.gz');
pipeline(read,write,
(err) => {
if (err) {
throw err
}
})
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
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
const functions = require('firebase-functions')
const { Storage } = require('#google-cloud/storage');
let gcs = new Storage ();
const os = require('os');
const path = require('path');
exports.onFileChange = functions.storage.object().onFinalize(event => {
console.log(event);
const bucket = event.bucket;
contentType = event.contentType;
const filePath = event.name;
console.log('file detected')
if(path.basename(filePath).startsWith('renamed-')){
console.log('already renamed this file')
return;
}
const destBucket = gcs.bucket(bucket);
const tmpFilePath = path.join(os.tmpdir(), path.basename(filePath));
const metadata = { contentType : contentType }
return destBucket.file(filePath).download({
destination : tmpFilePath
}).then(() => {
return destBucket.upload(tmpFilePath, {
destination:'renamed-'+ path.basename(filePath),
metadata: metadata
})
})
});
the error is:-
`Function failed on loading user code. Error message: Code in file index.js can't be loaded.
Is there a syntax error in your code?
Detailed stack trace: /srv/node_modules/p-limit/index.js:30
} catch {}
^
SyntaxError: Unexpected token {
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:617:28)
at Object.Module._extensions..js (module.js:664:10)
at Module.load (module.js:566:32)
at tryModuleLoad (module.js:506:12)
at Function.Module._load (module.js:498:3)
at Module.require (module.js:597:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (/srv/node_modules/#google-cloud/storage/build/src/bucke here t.js:25:16)
`
The error message implies you have a syntax error in your function.
Change the line contentType = event.contentType; to const contentType = event.contentType; and your syntax er
I am trying to parse a JSON file but getting an expected token, { at position 0.
SolaceConnetionParser.js
class SolaceConnectionParser {
constructor() { }
//TODO: cannot parse json correctly
parse(filepath) {
const connectionArgs = [];
console.log('File path: ' + filepath);
const rawData = fs.readFileSync(filepath, 'utf-8').toString;
const contents = JSON.parse(rawData);
return contents;
}
}
module.exports = SolaceConnectionParser;
const path = require('path');
const fs = require('fs');
const parser = new SolaceConnectionParser();
const filepath = path.join(__dirname + '../../../configs/test.json');
console.log(parser.parse(filepath));
test.json:
{
"key": "value"
}
Expected:
Rest of statements in code should output to console (i.e.: JSON contents).
Actual:
$ node SolaceConnectionParser.js
File path: C:\Users\u589329\Desktop\angular\dashboard_backend\dashboard_backend\src\configs\test.json
undefined:1
{
^
SyntaxError: Unexpected token in JSON at position 0
at JSON.parse (<anonymous>)
at SolaceConnectionParser.parse (C:\Users\u589329\Desktop\angular\dashboard_backend\dashboard_backend\src\app\solace\SolaceConnectionParser.js:9:31)
at Object.<anonymous> (C:\Users\u589329\Desktop\angular\dashboard_backend\dashboard_backend\src\app\solace\SolaceConnectionParser.js:26:31)
at Module._compile (internal/modules/cjs/loader.js:701:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
at Module.load (internal/modules/cjs/loader.js:600:32)
at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
at Function.Module._load (internal/modules/cjs/loader.js:531:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)
at startup (internal/bootstrap/node.js:283:19)
JSON objects are represented as Strings and fs.readFileSync() returns a Buffer.
Change
const rawData = fs.readFileSync(filepath, 'utf-8');
to
const rawData = fs.readFileSync(filepath, 'utf-8').toString();
and you should be good to go.
after applying Rob Raisch's answer and also trimming the string, problem was solved.
const rawData = fs.readFileSync(filepath, 'utf-8').toString().trim();