Error while doing module.exports = client; - javascript

I have a commands folder containing files that contains slash commands, and i have to import the client instance from index.js to another file, but when doing :
module.exports = client;
it execute the entire index.js script ! I don't know what I'm doing wrong, I tried to make the instance in another file than index.js and then import the instance in index, but it doesn't work. Can someone help me?

At least from what I'm understanding, (assuming you already had registered the commands and had a client object set up) you could pass client through into command.execute() as an argument (on the 10th line in the snippet):
in index.js:
client.on(Events.InteractionCreate, async interaction => {
if (!interaction.isChatInputCommand()) return;
const command = interaction.client.commands.get(interaction.commandName);
if (!command) {
console.error(`No command matching ${interaction.commandName} was found.`);
return;
}
try {
console.log(`running command "${interaction.commandName}"!`);
await command.execute(interaction,client);
} catch (error) {
console.error(error);
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}
});
And then take that argument within the command's module:
In commands/yourcommand.js:
module.exports = {
//[...] other slash command setup bits and bobs
async execute(interaction, client) {
// your code here
}
}
modified version of discordjs guide snippets
Feel free to ask if there's any need for elaboration or clarification; hope this helps & cheers!

Most objects in discord.js have access to the client, using simply .client. Notice the Base class has a .client property, and all interactions extend BaseInteraction, which extends Base. This means using interaction.client will give you access to the client.
async execute(interaction) {
const client = interaction.client
}

Related

What is the Vercel version of .netlify/functions?

I am trying to deploy this repo: https://github.com/DataStax-Examples/astra-tik-tok with Vercel instead of Netlify.
I refactored vanilla React into Next.js, but in the Home.js file I don't understand how to migrate this over to Vercel's equivalent:
//fetch all the tik-tok posts to your feed
const fetchData = async () => {
const results = await axios.get('/.netlify/functions/posts')
console.log(results.data)
setUsers(results.data)
}
Any ideas?
The equivalent in Next.js are API routes, which get deployed as serverless functions in Vercel. They must be created under the /pages/api folder.
You need to slightly refactor the functions to work with Next.js. For example, your add.js function would look like the following as an API route.
// /pages/api/add.js
export default function handler(req, res) {
const users = await getCollection();
try {
const user = await users.create(id, event.body);
res.status(200).json(user);
} catch (e) {
console.error(e);
res.status(500).json({ error: JSON.stringify(e) })
}
};
You would then call the API route from the client-side code by pointing to /api/add.
await axios.get('/api/add')

How to use module.exports in expressJs?

So i was making this discord bot thing with discord js and i wanted to add some frontend to like change some things using website and not commands buut i cant or i just dont know how to
use module.exports in expressjs i tried some stuff like this
var server = website.listen(8080, function() {
var port = server.address().port;
console.log("Server started at http://localhost:%s", port);
});
and this
website.use('/vars.js', main)
but none of it works ;;-;
edit: I forgot to mention but "main" is module in vars.js
(code of vars.js)
module.exports = {
"token": process.env.DISCORDJS_BOT_TOKEN,
"creator": process.env.mainUserID,
"creatorPing": "<#" + process.env.mainUserID + ">",
"status": "Ay Bros",
"version": "2.0.7"
}
next edit:
I dont really want to export functions from this file but variables, bacause functions cant change my bot status, i want to be able to modify the variables so my bot will change its status :P
It depends how you want to export your main function. You can do it these ways:
Using default export/import
// vars.js
function main() {...}
module.exports = main;
// root file
const main = require('./vars.js');
website.use(main);
Using named export/import:
// vars.js
function main() {...}
module.exports = { main };
// root file
const { main } = require('./vars.js');
website.use(main);
Another problem you have is wrong usage of .use function. It should receive a function, not a filename. So you need to import function and then use it, as I did in examples.
It depends on how to export the function you want but almost developer follows this pattern to exports functions in nodejs.
function getUser() {
// Code here
}
function getUsers() {
// Code here
}
module.exports = {
getUser,
getUsers
}
This would output:
getUser: [Function: getUser], getUsers: [Function: getUsers] }
This gives us function names and documents the API clearly at the end of the file and this pattern name is revealing the module pattern.

Testcafe throws an error invalid arg type

I try to write some basic e2e tests with testcafe on a React/Electron app. First I wrote a basic test getting the app Page Title:
App.e2e.js
import { Selector } from 'testcafe';
fixture`Electron App`.page('../../app/app.html');
test('should contain expected page title', async browser => {
await browser.expect(getPageTitle()).eql('Electron App');
});
The aboove test, it worked well!
But now I'm trying to add other tests like trying to login into the app with the next example:
App.e2e.js
import { Selector, Role } from 'testcafe';
const UserRole = Role('../../app/app.html', async t => {
await t
.typeText('input[name="email"]', 'user#user.com')
.typeText('input[name="password"]', 'secret')
.click(Selector('button[type=submit]').withText('Login'));
});
fixture`Electron App`
.page('../../app/app.html')
.beforeEach(async t => {
await t.useRole(UserRole);
});
test('Click a doc', async t => {
await t
.click(Selector('span').withText('Document'))
.expect(Selector('h1').withText('Document').exists)
.ok();
});
When I try to run e2e tests, I get a weird error like this:
Console output
ERROR Cannot prepare tests due to an error.
TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined
at resolveFileUrl (C:\Users\user\Git\electronApp\node_modules\testcafe\src\api\test-page-url.js:20:30)
at Object.resolvePageUrl (C:\Users\user\Git\electronApp\node_modules\testcafe\src\api\test-page-url.js:42:16)
at Proxy.createRole (C:\Users\user\Git\electronApp\node_modules\testcafe\src\role\index.js:73:17)
at Role (C:\Users\user\Git\electronApp\node_modules\testcafe\src\api\exportable-lib\index.js:15:17)
at Object.<anonymous> (C:\Users\user\Git\electronApp\tests\e2e\App.e2e.js:8:18)
at Function._execAsModule (C:\Users\user\Git\electronApp\node_modules\testcafe\src\compiler\test-file\api-based.js:50:13)
at ESNextTestFileCompiler._runCompiledCode (C:\Users\user\Git\electronApp\node_modules\testcafe\src\compiler\test-file\api-based.js:150:42)
at ESNextTestFileCompiler.execute (C:\Users\user\Git\electronApp\node_modules\testcafe\src\compiler\test-file\api-based.js:174:21)
at ESNextTestFileCompiler.compile (C:\Users\user\Git\electronApp\node_modules\testcafe\src\compiler\test-file\api-based.js:180:21)
at Compiler._getTests (C:\Users\user\Git\electronApp\node_modules\testcafe\src\compiler\index.js:86:31)
Type "testcafe -h" for help.
error Command failed with exit code 1.
It seems like testcafe can't find the correct path to launch the electron app, but in the first case the test worked with the same path. Is there something I'm missing?
Relative URLs in Roles are not supported yet. Keep track of this issue: Support relative urls in Roles. As a workaround, you can use an absolute path.

Node.js use mssql for accessing database

I'm making the Meteor.js app and I have to get data from mssql database. I use Meteor 1.8 and a npm package - mssql(version 5.1.0). That's my code:
const sql = require('mssql')
const config = {something}
export default function fetch(query) {
const config = {something}
sql.connect(config, err => {
if (err) {
console.error(err)
return
}
// create Request object
var request = new sql.Request()
// query to the database and get the records
request.query(query, (err, recordset) => {
if (err) {
console.error(err)
return
}
return recordset
})
})
}
And I have such error
TypeError: sql.connect is not a function
I don't know what's going on, I tried to do it in many ways and I failed. When I use ConnectionPool I see an error saying that ConnectionPool is not a constructor.
What is the proper way to do this?
In my config file I have: user, password, server, database, port.
It appears to be because you're mixing your module systems, you're using require (which is CommonJS-like) but in something that's apparently an ECMAScript module (ESM) (from the export default ...). Node.js itself won't let you do that, but if you're using some kind of bundler or transpiler, perhaps it might...
Changing your require to:
import sql from "mssql";
...and making sure Node.js is using ESM¹, I don't get any error with sql.connect not being a function.
¹ In my case, since I'm using Node.js v12, I do that by having "type": "module" in my package.json and running it via node --experimental-modules filename.js, more here.

import svg files inside meteor

I'm working on a project using meteor + react as front-and-back end.
For front-end UI, I am using element-react (https://eleme.github.io/element-react/#/en-US/quick-start) which is really cool and awesome. However when I tried to import element-react into my project (as instructed in the quick start of element-react homepage), meteor failed to compile static files and returned "Uncaught Error: Cannot find module './assets/error.svg''" which is the file do exist and has correct relative path.
Is there something missing or in meteor we simply can not use "require('./assets/error.svg')" to load a svg image?
According to this post in Meteor's forum.
You can use something like Meteor methods and the Assets API to get most any data from your server though. Something like
/server/main.js
Meteor.methods({
'svg.get'(data) {
return Assets.getText(data.path)
}
})
and
/client/main.js
const getSVG = async (path) => {
return await new Promise((resolve, reject) => {
Meteor.call('svg.get', { path }, (err, res) => {
if (err) reject('Something went wrong')
resolve(res)
})
})
}
const SVG = await getSVG('some/path/relative/to/private/file.svg')

Categories

Resources